2
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
}

为什么我的文本文件更改后此事件会跳转两次?

4

1 回答 1

1

这是避免事件引发的示例。

public void OnChanged(object source, FileSystemEventArgs e)
{
    FileSystemWatcher watcher = null;
    try
    {
        watcher = (FileSystemWatcher)source;
        watcher.EnableRaisingEvents = false;
    }
    finally
    {
        if (watcher != null)
        {
            watcher.EnableRaisingEvents = true;
        }
    }
}
于 2016-10-25T13:41:39.680 回答