Skip to content

Commit 88a1d27

Browse files
committed
added comments
1 parent 7bef041 commit 88a1d27

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

App/Services/SettingsManager.cs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff 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
{

0 commit comments

Comments
 (0)