【问题标题】:FileSystemWatcher raised event twice [duplicate]FileSystemWatcher 两次引发事件 [重复]
【发布时间】:2013-09-13 23:01:28
【问题描述】:
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
}

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

【问题讨论】:

标签: c#


【解决方案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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多