FileSystemWatcher无法正常工作WPF

时间:2016-12-08 09:27:53

标签: c# wpf mvvm filesystemwatcher

FileSystemWatcher无法正常工作。它仅在第一次更改发生时才响应。如果我然后更改第二个文件,则没有任何反应。

public class ImageViewModel : INotifyPropertyChanged
{
    public static ImageViewModel singletonInstance { get; set; }

    FileSystemWatcher watcher;
    private readonly BackgroundWorker worker1;

    public ImageViewModel()
    {
        ...

        watcher = new FileSystemWatcher(RootPath);
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;
        watcher.Changed += new FileSystemEventHandler(watcher_Changed);

        this.worker1 = new BackgroundWorker();
        this.worker1.DoWork += this.DoWork1;
        this.worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker1_Completed);
    }

    ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        editedFile = e.FullPath;

        if (worker.IsBusy == true || worker1.IsBusy == true)
        {
            autoEvent.WaitOne();
        }

        else
        {
            this.worker1.RunWorkerAsync();
        }
    }
}

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

在您通过调用AutoResetEvent的Set()方法发出信号之前,不会再次调用watcher_Changed事件处理程序。以下调用将阻止UI线程,当它被阻止时,它无法处理任何事件:

autoEvent.WaitOne();

如果你暂时从watcher_Changed事件处理程序中删除所有代码,只是在那里设置一个断点并调试你的应用程序,你应该看到它实际上被每个文件更改命中:

private void watcher_Changed(object sender, FileSystemEventArgs e)
{
    int d = 1; // set a breakpoint on this line, debug your application and modify the file
}

但请记住始终发布一个最小的,可编辑的和可运行的问题样本。