File tree Expand file tree Collapse file tree 1 file changed +11
-6
lines changed Expand file tree Collapse file tree 1 file changed +11
-6
lines changed Original file line number Diff line number Diff line change @@ -98,18 +98,23 @@ private void Save(string name, bool value)
9898 {
9999 try
100100 {
101- // Ensure cache is loaded before saving
101+ // We lock the file for the entire operation to prevent concurrent writes
102102 using var fs = new FileStream ( _settingsFilePath ,
103103 FileMode . OpenOrCreate ,
104104 FileAccess . ReadWrite ,
105105 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 ) ?? [ ] ;
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 }
114119 catch
115120 {
You can’t perform that action at this time.
0 commit comments