异常的多线程应用程序。 [英] Exceptions in multithreaded application.

查看:133
本文介绍了异常的多线程应用程序。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

解决方案

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

您可以挂接到<一个捕获这些异常(通常是记录他们) href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx">AppDomain.UnhandledException.请参阅页的详细信息,其中包括差异Windows窗体应用程序,等等。

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.

这篇关于异常的多线程应用程序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆