@@ -98,18 +98,23 @@ private void Save(string name, bool value)
98
98
{
99
99
try
100
100
{
101
- //Ensure cache is loaded before saving
101
+ //We lock the file for the entire operation to prevent concurrent writes
102
102
using var fs = new FileStream ( _settingsFilePath ,
103
103
FileMode . OpenOrCreate ,
104
104
FileAccess . ReadWrite ,
105
105
FileShare . None ) ;
106
-
107
- var currentCache = JsonSerializer . Deserialize < Dictionary < string , JsonElement > > ( fs ) ?? new ( ) ;
106
+
107
+ // Ensure cache is loaded before saving
108
+ var currentCache = JsonSerializer . Deserialize < Dictionary < string , JsonElement > > ( fs ) ?? [ ] ;
108
109
_cache = currentCache ;
109
110
_cache [ name ] = JsonSerializer . SerializeToElement ( value ) ;
110
- fs . Position = 0 ; // Reset stream position to the beginning before writing to override the file
111
- var options = new JsonSerializerOptions { WriteIndented = true } ;
112
- JsonSerializer . Serialize ( fs , _cache , options ) ;
111
+ fs . Position = 0 ; // Reset stream position to the beginning before writing
112
+
113
+ JsonSerializer . Serialize ( fs , _cache , new JsonSerializerOptions { WriteIndented = true } ) ;
114
+
115
+ // This ensures the file is truncated to the new length
116
+ // if the new content is shorter than the old content
117
+ fs . SetLength ( fs . Position ) ;
113
118
}
114
119
catch
115
120
{