There are multiple places in an application which call XmlWriter.Create on the same file, all accessed through the following function. When one calls while another is still writing, I get an IOException. What's the best way to lock or synchronize access?
Here's the function that's being used:
public void SaveToDisk()
{
try
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(SaveFileAbsolutePath, settings))
{
XamlWriter.Save(this, writer);
writer.Close();
}
}
catch (Exception ex)
{
// Log the error
System.Diagnostics.Debug.WriteLine(ex.Message);
// Rethrow so we know about the error
throw;
}
}
UPDATE: It looks like the problem isn't just from calls to this function, but because another thread is reading the file while this function is writing to is. What's the best way to lock so we don't try to write to the file while it's being read?