Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice to recover from a FileSystemWatcher error?

After a FileSystemWatcher.Error event was raised, I have no clue about what to do next. The exception can be a [relatively] minor one, such as

too many changes at once in directory

which doesn't affect the watcher's watching process, but it can also be a big issue - such as the watched directory being deleted, in which case the watcher is no longer functional.

My question is what is the best way to handle the Error event?

like image 381
Nissim Avatar asked Jul 26 '12 10:07

Nissim


2 Answers

Depends on the error surely?

  1. If it is too much data because the buffer was overrun (many changes) do a list directory and grab the changes you're after.
  2. If it is too much data because you're not processing the FileSystemWatcher events quickly enough, ensure you're processing it efficiently.
  3. Deleted directory, can't do anything about it other than disposing the FileSystemWatcher, or maybe watching the parent for a recreation of that directory name again.
like image 153
M Afifi Avatar answered Oct 18 '22 18:10

M Afifi


I would simply get the inner exception type, then decide on a per-error basis what to do ( restart or fail ).

So

myWatcher.Error += new ErrorEventHandler(OnError);

Followde by

private static void OnError(object source, ErrorEventArgs e)
{
    if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
    {
        //  This can happen if Windows is reporting many file system events quickly 
        //  and internal buffer of the  FileSystemWatcher is not large enough to handle this
        //  rate of events. The InternalBufferOverflowException error informs the application
        //  that some of the file system events are being lost.
        Console.WriteLine(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
    }
}
like image 1
John Mitchell Avatar answered Oct 18 '22 19:10

John Mitchell