What happens when a .NET thread throws an exceptio

2020-01-31 04:42发布

We have an interface IPoller for which we have various implementations. We have a process that will take an IPoller and start it in a separate thread. I'm trying to come up with a generic way of providing exception handling for any IPollers which don't do it themselves.

My original thinking was to create an implementation of IPoller that would accept an IPoller and just provide some logging functionality. The question I ran into though is how would I provide this error handling? If I have IPoller.Start() which is the target for the Thread is that where the exception will occur? Or is there something on the thread itself I can hook into?

5条回答
仙女界的扛把子
2楼-- · 2020-01-31 04:54

Something like:

Thread thread = new Thread(delegate() {
    try
    {
        MyIPoller.Start();
    }
    catch(ThreadAbortException)
    {
    }
    catch(Exception ex)
    {
        //handle
    }
    finally
    {
    }
});

This will ensure the exception doesn't make it to the top of the thread.

查看更多
Anthone
3楼-- · 2020-01-31 04:54

Take a look at AppDomain.UnhandledException, it will help you at least log those exceptions that you are not handling, and in some cases close down "nicely":

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.

查看更多
看我几分像从前
4楼-- · 2020-01-31 04:56

You should catch the exception at the method you use at the top of the thread, and do the logging from there.

An unhandled exception (at the top of a thread) will (in 2.0 onwards) kill your process. Not good.

i.e. whatever method you pass to Thread.Start (etc) should have a try/catch, and do something useful in the catch (logging, perhaps graceful shutdown, etc).

To achieve this, you could use:

  • static logging methods
  • captured variables into the delegate (as an anonymous method)
  • expose your method on an instance that already knows about the logger
查看更多
▲ chillily
5楼-- · 2020-01-31 04:57

Have a look at

Appdomain.FirstChanceException event

It tells you moment any exception occurs and CLR is looking for stack trace. Also event args tell which type of exception. You can consider it as the central place for logging.

查看更多
贪生不怕死
6楼-- · 2020-01-31 04:58

In .NET 4.0+ you should use Tasks instead of threads. Here's a nice article on exception handling in Task Parallel Library

查看更多
登录 后发表回答