文件系统观察器引发事件两次
本文关键字:两次 事件 观察 文件系统 | 更新日期: 2023-09-27 18:31:12
public void startWatch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Path.GetDirectoryName(_file);
watcher.Filter = Path.GetFileName(_file);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += watcher_Changed;
watcher.EnableRaisingEvents = true;
}
public void watcher_Changed(object sender, FileSystemEventArgs e)
{
// Jump twice
}
为什么在我的文本文件更改后,此事件会跳转两次?
下面是避免引发事件的示例。
public void OnChanged(object source, FileSystemEventArgs e)
{
FileSystemWatcher watcher = null;
try
{
watcher = (FileSystemWatcher)source;
watcher.EnableRaisingEvents = false;
}
finally
{
if (watcher != null)
{
watcher.EnableRaisingEvents = true;
}
}
}