@@ -98,18 +98,23 @@ private void Save(string name, bool value)
9898{
9999try
100100{
101- //Ensure cache is loaded before saving
101+ //We lock the file for the entire operation to prevent concurrent writes
102102using var fs = new FileStream ( _settingsFilePath ,
103103FileMode . OpenOrCreate ,
104104FileAccess . ReadWrite ,
105105FileShare . 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 ) ?? [ ] ;
108109_cache = currentCache ;
109110_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 ) ;
113118}
114119catch
115120{