There’s situations where you want to read or write a file and get an exception because the file cannot be accessed for some reason. The reason usually is another process/app/thread also accessing the file in the very same moment.
To circumvent this, I used mutex and that solved the issues at least for my usecase.
I raise this topic here, because I think this could be a nice addition to the corelib.
Please see the attached code and demo:
MutexDemo.7z (11.2 KB)
The demo is very simplified… you can try to read/write the test.txt file with another application while the patch is running and try to break it.
The code is not made for general use and should be adapted to be a proper node - but before that, let’s find out if this is a way to go or if there are still some edgecases or other pitfalls.
This is the gist:
public static Mutex s_Mutex = new Mutex(false, @"Global\MutexSettingsFile");
/// <summary>
/// Write to the Settings file
/// </summary>
/// <param name="content"></param>
/// <param name="filepath"></param>
/// <param name="timeout"></param>
public static void Write(string content, string filepath, double timeout = 5)
{
try
{
s_Mutex.WaitOne(TimeSpan.FromSeconds(timeout));
Utils.CreateFileIfNotExist(filepath);
using (StreamWriter w = new StreamWriter(filepath, false, Encoding.UTF8))
{
w.Write(content);
}
}
catch (Exception e)
{
Console.WriteLine("error writing to settings file:" + e.Message);
}
finally
{
s_Mutex.ReleaseMutex();
}
}