Different approach
MODIFY
WalletWasabi/Bases/ConfigBase.cs
WalletWasabi/Bases/ConfigBase.cs
@@ -27,7 +27,6 @@ public abstract class ConfigBase : NotifyPropertyChangedBase, IConfig
protected object FileLock { get; } = new();
/// <inheritdoc/>
- /// <remarks>Use <see cref="ReadFile"/> and <see cref="WriteFile(string)"/> for I/O operations (<see cref="File.Exists(string?)"/> does not require locking).</remarks>
public string FilePath { get; private set; } = "";
/// <inheritdoc/>
@@ -49,17 +48,23 @@ public abstract class ConfigBase : NotifyPropertyChangedBase, IConfig
throw new FileNotFoundException($"{GetType().Name} file did not exist at path: `{FilePath}`.");
}
- string jsonString = ReadFile();
+ lock (FileLock)
+ {
+ string jsonString = ReadFileLocked();
object newConfigObject = Activator.CreateInstance(GetType())!;
JsonConvert.PopulateObject(jsonString, newConfigObject, JsonSerializationOptions.Default.Settings);
return !AreDeepEqual(newConfigObject);
}
+ }
/// <inheritdoc />
public virtual void LoadOrCreateDefaultFile()
{
AssertFilePathSet();
+
+ lock (FileLock)
+ {
JsonConvert.PopulateObject("{}", this);
if (!File.Exists(FilePath))
@@ -70,7 +75,7 @@ public abstract class ConfigBase : NotifyPropertyChangedBase, IConfig
{
try
{
- LoadFile();
+ LoadFileLocked();
}
catch (Exception ex)
{
@@ -79,19 +84,16 @@ public abstract class ConfigBase : NotifyPropertyChangedBase, IConfig
}
}
- ToFile();
+ ToFileLocked();
+ }
}
/// <inheritdoc />
public virtual void LoadFile()
{
- string jsonString = ReadFile();
-
- JsonConvert.PopulateObject(jsonString, this, JsonSerializationOptions.Default.Settings);
-
- if (TryEnsureBackwardsCompatibility(jsonString))
+ lock (FileLock)
{
- ToFile();
+ LoadFileLocked();
}
}
@@ -112,28 +114,42 @@ public abstract class ConfigBase : NotifyPropertyChangedBase, IConfig
/// <inheritdoc />
public void ToFile()
+ {
+ lock (FileLock)
+ {
+ ToFileLocked();
+ }
+ }
+
+ protected virtual bool TryEnsureBackwardsCompatibility(string jsonString) => true;
+
+ protected void LoadFileLocked()
+ {
+ string jsonString = ReadFileLocked();
+
+ JsonConvert.PopulateObject(jsonString, this, JsonSerializationOptions.Default.Settings);
+
+ if (TryEnsureBackwardsCompatibility(jsonString))
+ {
+ ToFileLocked();
+ }
+ }
+
+ protected void ToFileLocked()
{
AssertFilePathSet();
string jsonString = JsonConvert.SerializeObject(this, Formatting.Indented, JsonSerializationOptions.Default.Settings);
- WriteFile(jsonString);
+ WriteFileLocked(jsonString);
}
- protected void WriteFile(string contents)
- {
- lock (FileLock)
+ protected void WriteFileLocked(string contents)
{
File.WriteAllText(FilePath, contents, Encoding.UTF8);
}
- }
- protected string ReadFile()
- {
- lock (FileLock)
+ protected string ReadFileLocked()
{
return File.ReadAllText(FilePath, Encoding.UTF8);
}
}
-
- protected virtual bool TryEnsureBackwardsCompatibility(string jsonString) => true;
-}

Different approach