Search code examples
c#wpfmvvmfilesystemwatcher

FileSystemWatcher doesnt work properly WPF


FileSystemWatcher does not work properly. It only responds when the first change occurs. If I then change a second file, nothing happens.

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

Can you help me solve this problem?


Solution

  • The watcher_Changed event handler won't be invoked again until you signal by calling Set() method of the AutoResetEvent. The following call will block the UI thread and while it is blocked it cannot handle any events:

    autoEvent.WaitOne();
    

    If you temporarily remove all your code from the watcher_Changed event handler and just set a breakpoint in there and debug your application you should see that it actually gets hit for each file change:

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

    But please remember to always post a a minimal, compilable and runnable sample of your issue.