异常的多线程应用程序。多线程、应用程序、异常

2023-09-03 17:19:10 作者:夺她心入她身

我已经听到了一个异常被抛出(并没有被捕获),在一个线程被传播到父线程一个很挑剔的人。真的吗? 我曾尝试这样的事情,但不能捕捉异常在创建线程。

 静态无效的主要(字串[] args)
    {
        ParameterizedThreadStart PTS =
           新ParameterizedThreadStart(ThreadMethod);
        尝试
        {
            线程t =新主题(PTS);
            t.Start(新的对象());
            到Console.ReadLine();
        }
        赶上(例外前)//该例外没有被捕获
        {
            Debugger.Break();
        }
    }


    静态无效ThreadMethod(对象@object)
    {
        Thread.sleep代码(2000);
        抛出新的IndexOutOfRangeException();
        Thread.CurrentThread.Abort();
    }
 

解决方案

线程的异常不会传播到主线程的上下文中。这确实是有道理的 - 被抛出异常的时候,主线程通常是在一个完全不同的范围比含有异常处理程序之一

您可以挂接到AppDomain.UnhandledException.请参阅页的详细信息,其中包括差异Windows窗体应用程序,等等。

C 规范整理 异常与自定义异常

I have heard from a very discerning person that an exception being thrown (and not caught) in a thread is being propagated to the parent thread. Is that true? I have tried something like this but couldn't catch the exception in the creating thread.

    static void Main(string[] args)
    {
        ParameterizedThreadStart pts = 
           new ParameterizedThreadStart(ThreadMethod);
        try
        {
            Thread t = new Thread(pts);
            t.Start(new object());
            Console.ReadLine();
        }
        catch (Exception ex) //the exception is not caught
        {
            Debugger.Break();
        }
    }


    static void ThreadMethod(object @object)
    {
        Thread.Sleep(2000);
        throw new IndexOutOfRangeException();
        Thread.CurrentThread.Abort();
    }

解决方案

The thread's exception will not propogate to the main thread's context. This really makes sense - by the time the exception is thrown, the main thread will typically be in a completely different scope than the one containing your exception handler.

You can catch these exceptions (typically to log them) by hooking into AppDomain.UnhandledException. See that page for details, including differences in Windows Forms applications, etc.