FFMG / myoddweb.directorywatcher

A fast and reliable, (non blocking!), .NET/C++ File/Directory watcher, complete rewrite of FileSystemWatcher to ensure speed/accuracy/reliability/suppress duplicate events.
MIT License
49 stars 12 forks source link

OnAddedAsync getting invoked multiple times #18

Closed Anirud-Thapliyal closed 3 years ago

Anirud-Thapliyal commented 3 years ago

I have a windows service on .net core which runs every 5 mins and watches the directory on a network drive. Below is the part of code which I am using to call OnAddedAsync whenever any file is placed in that directory:

public class ProcessFileWatcher { private Watcher watcher; }

public ProcessFileWatcher() { watcher = new Watcher(); }

// Inside Main method try { watcher.Add(new Request(folderToWatchFor, true)); watcher.OnAddedAsync += OnFileCreated; watcher.Start(); } catch (Exception ex) { _logger.LogError(ex, $"Unexpected error occurred while initializing File Watcher"); }

// OnAddedAsync event handler private async Task OnFileCreated(IFileSystemEvent e, CancellationToken token) { try { // Picks the file for further processing } catch(Exception ex) {

 }

}

After 5 mins service has been running, if I drop a file the OnFileCreated event handler gets invoked 2 times. Similarly, after 10 mins service has been running, if I drop a file the OnFileCreated event handler gets invoked 3 times. Or, if any exception occurs in OnFileCreated after 5 mins then same message gets logged twice.

Reason to run it in a loop of every 5 mins: When I am running from my local without loop, the watcher works fine and as expected. But after deployment, it fails to invoke the OnAddedAsync for the nested folders. Let's consider I create a folder2 inside folder1 and then I drop file inside folder2, it doesn't call OnAddedAsync event.

FFMG commented 3 years ago

Hum... thanks for that Let me set up a test environment and see if I can reproduce it

What do you mean when you say service on .net core which runs every 5 mins, can you explain it further?

Anirud-Thapliyal commented 3 years ago

It is a console application built on .Net Core and hosted as windows service on IIS. It delays the Task thread for 5 mins and executes again after every 5 mins,

So whenever it executes after every 5 mins, for that many times the OnAddedAsync gets invoked. And processes the code again even if it is not required. First time it will call OnAddedAsync 1 time. 2nd time it will call it 2 times, 3rd time 3 times and so on.