尝试catch来捕获.NET threadpool中的错误

Duk*_*ade 3 c# exception try-catch threadpool

在一个应用程序中,我注册了EventLog.EntryWritten事件,并使用.NET Threadpool线程等待更改事件发生.我认为这个.NET Threadpool线程中发生异常,所以我想使用try/catch来确保,如下所示:

try {
eventLog.EntryWritten += new EntryWrittenEventHandler(EventLogMonitor); 
}
catch (System.Componentmodel.Win32exception e)
{
// log error
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道我是否在正确的地方使用try/catch来监视此线程的异常?

Ash*_*her 6

您编写的代码将捕获事件注册的异常,而不是事件本身.

你应该在你的EventLogMonitor方法中放置try..catch块.

private void EventLogMonitor (Object sender,EntryWrittenEventArgs e)
{
     try
     { 
       // your logic goes here
     }
     catch (Exception ex)
     {
          //do something with the excpetion
     }

}
Run Code Online (Sandbox Code Playgroud)