c# FileSystemWatcher 在监听 OnChanged 时触发两次

c# FileSystemWatcher triggers twice when listening to OnChanged

正在尝试执行 FileSystemWatcher,但是 OnChanged 函数在保存文件时被调用了两次。根据其他一些帖子,我怀疑 LastWrite 过滤器有多个事件?我认为 NotifyFilters 会将其限制为仅在写入文件时触发,但其他原因导致函数 运行 两次。 e.ChangeType 只告诉我文件改变了,但没有告诉我具体是怎么改变的。有没有办法将此限制为 运行ning 一次?

    public MainWindow()
    {
        InitializeComponent();

        FileSystemWatcher fsw = new FileSystemWatcher(path);
        fsw.NotifyFilter = NotifyFilters.LastWrite;
        fsw.EnableRaisingEvents = true;
        fsw.Changed += new FileSystemEventHandler(OnChanged);
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (newString == null)
        {
            using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                lastString = sr.ReadToEnd();
            }
            difference = lastString;
        } else {
            using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                newString = sr.ReadToEnd();
            }
            int newCount = newString.Count();
            int count = lastString.Count();
            // MessageBox.Show("last:" + lastString.Count().ToString(), "next: " + newString.Count());
            difference = newString.Remove(0,5);
            lastString = newString;
        }
        Application.Current.Dispatcher.Invoke(new Action(() => { tb_content.Text = difference; }));
        MessageBox.Show(e.ChangeType.ToString(), "");
    }
}

你可以自己过滤掉,正如我发布的那样here

弗雷德里克答案的替代方案:

想到的一个小解决方法是阻止 OnChanged 方法在其已在执行的情况下执行。

例如:

private bool IsExecuting { get; set; }

private void OnChanged(object sender, FileSystemEventArgs e)
{
    if (!IsExecuting) 
    {
        IsExecuting = true;

        // rest of your code

        IsExecuting = false;
    }
}