当.NET线程抛出一个异常,会发生什么?线程、抛出、异常、发生

2023-09-03 00:50:00 作者:清酒尹歌°

我们有一个接​​口IPoller对此我们有不同的实现。我们有一个过程,将采取的IPoller和在单独的线程启动它。我试图想出提供异常处理任何IPollers不自己做了一个通用的方法。

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.

我最初的想法是创建IPoller的实现,将接受IPoller,只是提供一些日志记录功能。我虽然碰到的问题是如何将我提供这个错误处理?如果我有IPoller.Start(),这是该线程的目标是,将发生异常?或者是有什么线程本身上我可以挂接到?

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?

推荐答案

是这样的:

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.