C# Catching exception which is occurring on ThreadPool

六月ゝ 毕业季﹏ 提交于 2019-12-05 01:31:26

If I understand you correctly (it would help if you pass the stacktrace that leads you to the conclusion that the exception is happening inside a threadpool thread), then just wrap your code of EventLogMonitor in a try/catch block.

Example:

void EventLogHandler(object sender, EventArgs args)
{
   try
   {
      // Your original code.
   }
   catch (Exception ex)
   {
      // Log or Write "ex" to the console. Set a breakpoint, whatever.

      throw;
   }
}

UPDATE: after your update it looks as if the exception is indeed not raised from inside your handler, but before it is even called inside the EventLog class.

You could try registering a handler with the AppDomain.UnhandledException event and do your logging/handling in there. Note that this will not allow you to suppress or "change" or wrap the exception, but merely to log it somewhere for diagnostic purposes.

If you just want to inspect the exception once (or on occasion), you should try using the SOS-extension's !PrintException command in WinDBG.

UPDATE 2: after further investigation I find it rather strange that the exception bubbles up all. Your stacktrace suggests you're using .NET 3.5 (or earlier, but not 4.) and looking at the EventLog class in Reflector you can see that the whole handling of the EventWrittenHandler, including the preamble code that seems to cause the exception, is wrapped in one big "try/catch(Exception)/catch" block. Funny.

Subscribe to Application.ThreadException in your Program.cs as follows to be able to catch the exceptions that are not in main thread.

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += Application_ThreadException;
        try
        {
            Application.Run(new MainForm());
        }
        catch (Exception e)
        {
            HandleException(e);
        }
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        HandleException(e.Exception);
    }
NPehrsson
  1. If you can, use Tasks in System.Threading.Tasks.
  2. Try, where action is performing what you want.

    ThreadPool.QueueUserWorkItem(state =>
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            OnException(ex);
        }
    });
    

Not sure what kind of Application this is, so in a general case, if you're having no luck, try hooking into the AppDomain in which the code is running. If you don't have multiple domains, you can try:

AppDomain.CurrentDomain.FirstChanceException += Handler

or

AppDomain.CurrentDomain.UnhandledException += Handler

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