应用程序中有多个位置在同一个文件上调用 XmlWriter.Create,所有位置都通过以下函数访问。当一个人打电话而另一个人还在写信时,我得到一个 IOException。锁定或同步访问的最佳方式是什么?
这是正在使用的功能:
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;
}
}
更新:看起来问题不仅来自对该函数的调用,还因为另一个线程正在读取该文件,而该函数正在写入。什么是最好的锁定方式,这样我们就不会在读取文件时尝试写入文件?