我有一些包含数据的存档文件,我有一些写入该存档文件的线程,在主线程中,我有文件系统监视程序,当发生某些更改时,该系统读取文件内容:
static FileSystemWatcher watcher = new FileSystemWatcher();
string archPath=@"C:\arch.xml";
public MyClass()
{
watcher.Path = dir;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime;
watcher.Filter = Path.GetFileName("*" + archPath);
watcher.Changed += OnFileChanged;
watcher.Created += OnFileCraeted;
watcher.EnableRaisingEvents = true;
}
public void OnFileChanged(object source, FileSystemEventArgs e)
{
try
{
watcher.EnableRaisingEvents = false;
LoadArchive();
}
finally
{
watcher.EnableRaisingEvents = true;
}
}
void LoadArchive()
{
DataSet ds = new DataSet();
ds.ReadXml(archPath); /// <----this line throws exeption
}
System.IO.IOException:该进程无法访问文件'C:\ arch.xml',因为它正在被另一个进程使用。
我的问题:我想在内容有所变化时阅读内容,如何避免这种情况发生?