在线程异常处理 [英] Exception handling in threads

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

问题描述

最近,我参加面试。一个代码片断给我。我知道,面试官把它从albhari的线程样本。

Recently i have attended an interview . A code snippet is given to me.I know,the interviewer took it from albhari's threading sample.

public static void Main() 
{
    try 
    {
        new Thread (Go).Start();
    }
    catch (Exception ex)
    {
        // We'll never get here!
       Console.WriteLine ("Exception!");
    }
}

static void Go() { throw null; }



上面的代码为

The modification of the above code as

public static void Main()
{
    new Thread (Go).Start();
}

static void Go() 
{
    try 
    {
        ...
        throw null; // this exception will get caught below
        ...
    }
    catch (Exception ex) 
    {
        Typically log the exception, and/or signal another thread
        that we've come unstuck
        ...
    }
}

将是不错的人选来处理异常。

would be the good candidate to handle the exception.

有人问我,除了上面的踪迹什么其他的替代品将适合作为很好的解决方案?这是很难找到替代品,所以我在这里提出来收集你的建议。

I have been asked, "Except the above trail what are the other alternatives would fit as good solution?. It was hard to find the alternative,so i raise it here to gather your suggestion.

推荐答案

例外在一个线程中抛出通常不能在另一个线程被抓住。

Exception thrown in a thread normally couldn't be caught in another thread.

您最好赶上它的功能你去把它传递给主线程明确。

You'd better to catch it in function Go and pass it to main thread explicitly.

不过,如果你只是想从所有线程记录所有未处理的邮件,你可以使用的 AppDomain.UnhandledException 事件或等效事件的,如果你正在开发的WinForms或WPF应用程序应用程序类。

However, if you just want to log all unhandled messages from all threads, you may use AppDomain.UnhandledException event or equivalent events at Application class if you are developing WinForms or WPF app.

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

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