dimanche 15 août 2021

FileSystemWatcher: using multiple filters result in calling the same method mutiple times in a row

Take the following code, the events raised by the watcher all call the same method:

[NonSerialized]
private FileSystemWatcher Watcher;

private void WatcherInit()
{
    Watcher ??= new FileSystemWatcher();

    Watcher.Path                  = Application.dataPath;
    Watcher.Filter                = "*.mat";
    Watcher.IncludeSubdirectories = true;
    Watcher.NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.CreationTime;

    Watcher.EnableRaisingEvents = true;

    Watcher.Changed += OnWatcherChanged;
    Watcher.Created += OnWatcherCreated;
    Watcher.Deleted += OnWatcherDeleted;
    Watcher.Renamed += OnWatcherRenamed;
}

private void OnWatcherRenamed(object sender, RenamedEventArgs args)
{
    DoViewReload();
}

private void OnWatcherDeleted(object sender, FileSystemEventArgs args)
{
    DoViewReload();
}

private void OnWatcherCreated(object sender, FileSystemEventArgs args)
{
    DoViewReload();
}

private void OnWatcherChanged(object sender, FileSystemEventArgs args)
{
    DoViewReload();
}

This results in the same method called multiple times while I'd like it to be only once.

In my case, I refresh the UI and it happens 3 times when I create a new file.

I suppose there should be some timer that would wait for successive events and concat them, then only emit a single call; that's just a guess and maybe there's a better solution around that I'm not aware of.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire