I have a multi threaded application that writes to a settings xml file using a static method. I want to avoid that the file is being updated twice at the same time (causing accesss/write exception).
How do I do that?
This doesn’t work:
namespace Program
{
public class Settings
{
private static void SetSettingsValue (string settings, string value)
{
// make this thread safe to avoid writing to a locked settings xml file
lock (typeof(Settings))
{
//write data to xml file
}
}
}
}
The concept of lock() is to use an existing-object it can reference and use to control whether access is granted.
When the execution leaves the lock() block the reference is released and any other threads waiting to execute the code block can proceed (one at a time, of course).