【发布时间】:2010-10-01 07:56:46
【问题描述】:
在同一个文件上调用 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;
}
}
更新:看起来问题不仅来自对该函数的调用,还因为另一个线程正在读取该文件,而该函数正在写入。什么是最好的锁定方式,这样我们就不会在读取文件时尝试写入文件?
【问题讨论】:
标签: c# file-io ioexception xmlwriter