【问题标题】:try catch to catch errors in .NET threadpool尝试 catch 以捕获 .NET 线程池中的错误
【发布时间】:2011-12-14 16:02:13
【问题描述】:

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

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

我只是想知道我的 try/catch 是否在正确的位置来监视此线程是否有异常?

【问题讨论】:

  • 你期望它会扔到哪里?它在事件订阅中吗?还是您希望EventLogMonitor 可能会抛出?
  • 我认为尝试将方法附加到 EntryWritten 事件时不会出现异常。所以 catch 块可能永远不会触发。如果您想捕获代码中可能发生的任何异常,您可以将 try 块包裹在整个方法/代码区域中。因此,例如在 EventLogMonitor 方法中......这根本不是最佳实践。

标签: c# exception try-catch threadpool


【解决方案1】:

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

您应该将 try..catch 块放在 EventLogMonitor 方法中。

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

}

【讨论】:

  • 因为异常不会跨线程传播,您可能还需要一种将捕获的异常传递给主线程的方法。然后主线程可以记录它/重新抛出它/显示它等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
相关资源
最近更新 更多