线程中的异常处理

use*_*805 9 c# multithreading

最近我参加了一次采访.给我一个代码片段.我知道,面试官是从albhari的线程样本中获取的.

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; }
Run Code Online (Sandbox Code Playgroud)

将上述代码修改为

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
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

将是处理异常的好候选人.

我被问到,"除了上面的描述,其他替代方案是否适合作为一个好的解决方案?.很难找到替代方案,所以我在这里提出来收集你的建议.

eld*_*rge 16

通常无法在另一个线程中捕获在线程中抛出的异常.

你最好在函数Go中捕获它并明确地将它传递给主线程.

但是,如果您只想记录来自所有线程的所有未处理消息,则可以在Application类中使用AppDomain.UnhandledException事件或等效事件(如果您正在开发WinForms或WPF应用程序).

  • ...但请注意,您无法处理AppDomain.UnhandledException中的异常,您会收到通知,但应用程序仍会关闭. (11认同)
  • 通过设置 v1.x 兼容模式可以防止应用程序停止。为此,必须将 <legacyUnhandledExceptionPolicyenabled="1"/> 元素添加到 <runtime 部分的 app.config 中 (2认同)