捕获FileSystemWatcher侦听器线程抛出的异常

问题描述 投票:1回答:1

我试图找出一种方法来捕捉FileSystemWatcher抛出的异常,这些似乎是随机发生的,正如我从我的软件的崩溃报告日志中注意到的那样。崩溃并不频繁,因为它上个月只发生了两次,但它很烦人,我很乐意解决它。有问题的例外似乎与路径中包含无效字符的文件有关。我不确定是否是这种情况,或者提出的事件是否格式错误。到目前为止,我所知道的是异常的堆栈跟踪:

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)

从堆栈跟踪中可以清楚地看到,在将回调事件提升到我的应用程序之前,会在侦听器的执行上下文中引发异常。我想知道是否有任何方法来捕获这样的异常并继续执行,忽略该事件。

我尝试使用try/catch块封装我的观察者回调的主体,但似乎执行从未到达回调并且它真的令人沮丧,因为我现在开始认为它是.Net框架中的一个错误

c# exception filesystemwatcher
1个回答
0
投票

您是否尝试过注册OnError事件?

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

编辑:

唯一剩下的就是ThreadException和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);
© www.soinside.com 2019 - 2024. All rights reserved.