从FileSystemWatcher错误中恢复的最佳做法是什么?

Nis*_*sim 6 .net c# filesystemwatcher exception-handling

经过一个FileSystemWatcher.Error引发事件,我不知道下一步该怎么做的线索.例外可以是[相对]次要的,例如

目录中一次更改太多

这不会影响观察者的观看过程,但它也可能是一个大问题 - 例如被监视的目录被删除,在这种情况下观察者不再起作用.

我的问题是处理Error事件的最佳方法是什么?

Joh*_*ell 1

我只需获取内部异常类型,然后根据每个错误决定要做什么(重新启动或失败)。

所以

myWatcher.Error += new ErrorEventHandler(OnError);
Run Code Online (Sandbox Code Playgroud)

跟随

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));
    }
}
Run Code Online (Sandbox Code Playgroud)