本文介绍了为什么在线程池线程引发的异常没有在C#中由主线程处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码片段。

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Thread m_thread = new Thread(() =>
                {
                    //try
                    //{
                        checkexc();
                    //}
                    //catch (Exception ex)
                    //{

                    //}
                }
                );
            m_thread.Start();

        }
        catch (Exception ex)
        {

        }
    }
    static void checkexc()
    {
        throw new NullReferenceException();
    }
}



的NullReferenceException不会被覆盖处理try-catch块。但是,如果我换线程()构造函数中的代表,那么它是由尝试捕获处理。为什么不列入外的try-catch处理这个异常。

NullReferenceException is not handled by the covering Try-Catch block. However if i wrap the delegate inside thread() constructor, then it is handled by that Try-Catch. Why doesnot outer Try-Catch handle this exception.

推荐答案

假设你有一个主路(A),另一路分支从路(b)。

Imagine you have a main road (A), and another road branches off from that road (B).

在一辆卡车沿A进入,如果它崩溃,那么A就知道这件事了,交通就会停止。

When a truck goes along A, if it crashes, then A will know about it, and traffic will stop.

在一辆卡车沿b进入,如果它崩溃,那么b就知道这件事了,交通就会停止。

When a truck goes along B, if it crashes, then B will know about it, and traffic will stop.

但是,是什么机制将区分A和B一辆卡车上已经坠毁?

But by what mechanism will B tell A that a truck has crashed on it?

在卡车上B,它不影响A,除非还有另外一个入口点的A为B。

Once the truck is on B, it is not affecting A, unless there is another entry point along A into B.

怎么会在你的其他线程异常通报给主线程?一旦其他线程运行时,它不再是(直接)与主线程通信。

How will the exception in your other thread be communicated to the main thread? Once the other thread is running, it no longer (directly) communicates with the main thread.

这篇关于为什么在线程池线程引发的异常没有在C#中由主线程处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 19:45