C# 文件系统监视程序无法正常工作WPF

C# 文件系统监视程序无法正常工作WPF,c#,wpf,mvvm,filesystemwatcher,C#,Wpf,Mvvm,Filesystemwatcher,FileSystemWatcher无法正常工作。它仅在第一次更改发生时响应。如果我随后更改第二个文件,则不会发生任何事情 public class ImageViewModel : INotifyPropertyChanged { public static ImageViewModel singletonInstance { get; set; } FileSystemWatcher watcher; private readonly BackgroundWorker

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();
        }
    }
}

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

在您通过调用AutoResetEvent的Set()方法发出信号之前,不会再次调用watcher\u 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
}

但请记住,一定要发布一个最小的、可编译且可运行的问题样本。

奇怪的是,你的观察者只工作一次。。您确定没有在更改的监视程序中禁用它吗?错误是什么?不能正常工作对我们没有帮助。后台工作人员与此有什么关系?为什么
watcher
字段不是
private readonly
,比如
worker1
?你在
watcher\u Changed
中做什么?请提供一个。不能正常工作->观察者只工作一次!你能发布
DoWork1
的代码吗?我使用了
autoEvent.WaitOne()
,因为我使用了两个BackgroundWorker,它们不应该同时运行。在一个后台工作人员开始完成任何事情之前,它应该一直等待另一个完成它的工作,然后自动开始。我怎么能意识到呢???这真的是另一个问题。但是您必须从某个地方调用autoReset.Set(),UI线程才能处理事件。例如,您可以在BackgroundWorker的RunWorkerCompleted事件的事件处理程序中执行此操作。但是如果你有其他问题,请问一个新问题。