Catching exceptions thrown by the FileSystemWatcher listener thread

混江龙づ霸主 提交于 2020-01-15 10:59:06

问题


I am trying to figure out a way to catch exceptions thrown by FileSystemWatcher these seem to happen randomly as I have noticed from the crash reports logs for my software. The crash is not frequent as it only happened twice last month but its annoying and I would love to fix it. The exception in question seems to be related to files having invalid characters in their paths. I am not sure if that is the case or if the event raised is malformed. So far all I know is the stack trace of the exception:

Top-level Exception
Type:        System.ArgumentException
Message:     Illegal characters in path.
Source:      mscorlib

    Stack Trace: 
    at System.IO.Path.GetFileName(String path)

    at System.IO.FileSystemWatcher.MatchPattern(String relativePath)

    at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)

    at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes,   NativeOverlapped* overlappedPointer)

    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

From the stack trace it is clear that the exception is raised within the execution context of the listener before raising the callback events to my application. I was wondering if there is anyway to catch such an exception and continue execution, ignoring the event.

I tried encapsulating my watcher callbacks' body with try/catch blocks but it seems that the execution never reaches the callbacks and its really frustrating as I am now starting to think that it is a bug in the .Net framework


回答1:


Have you tried registering the OnError event?

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.onerror%28v=vs.110%29.aspx

EDIT:

The only thing left is ThreadException and UnhandledException:

    // Add handler to handle the exception raised by main threads
    Application.ThreadException += 
    new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

    // Add handler to handle the exception raised by additional threads
    AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


来源:https://stackoverflow.com/questions/21450296/catching-exceptions-thrown-by-the-filesystemwatcher-listener-thread

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