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

一个人想着一个人 提交于 2020-01-11 08:42:06

问题


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?


回答1:


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.



回答2:


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


来源:https://stackoverflow.com/questions/11667041/whats-the-best-practice-to-recover-from-a-filesystemwatcher-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!