【发布时间】:2012-08-26 20:12:44
【问题描述】:
我有一个非常简单的线程。 Thread 对象所做的唯一事情是throw new Exception();。我这样做的原因是因为我需要测试如果在我的应用程序的单独线程中发生异常会发生什么。我已经用“真正的”运行时异常对此进行了测试,我的问题是一样的。
在调用线程之前我要做的是:
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
Application.Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException;
//To handle exceptions in another thread
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
//Do nothing ignore exception
}
//To handle all exceptions in main thread
private static void CurrentOnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs dispatcherUnhandledExceptionEventArgs)
{
dispatcherUnhandledExceptionEventArgs.Handled = true;
}
当该线程确实抛出异常时,它首先会按应有的方式命中CurrentDomainOnUnhandledException,然后它不会命中CurrentOnDispatcherUnhandledException。在CurrentDomainOnUnhandledException 之后,堆栈然后移回线程,在那里它抛出异常并再次抛出它,执行同一行。它永远不会停止这样做。这基本上是一个永无止境的循环,我不知道为什么。
UnhandledExceptionEventArgs 没有要设置的属性,表示我们已经处理了异常,我很确定这是问题的一部分。
我做错了什么,如何在这个线程中捕获这个 UnhandledException,并让线程继续执行(首选)或中止/杀死线程(非首选),使其不会继续执行 throw new异常行。
我已经通过调试和发布对此进行了测试(确保发布时的调试信息设置为无),这仍然在两个版本中发生,异常继续一遍又一遍地发生。
提前谢谢,我很困惑,不知道为什么会这样。
【问题讨论】:
-
在未捕获的异常之后,线程不可能继续执行。它会运行什么代码?抛出异常的全部目的是专门防止下一行代码执行。这就像在代码中出现
return之后试图留在函数中一样。我不知道你为什么认为你需要这样做,但我很确定你是从某个地方的根本误解开始的。 -
嗯,你让我信服了,没办法弥补。这将是一个非常严重的 CLR 错误。请记录您使用的 .NET 版本并发布启动线程并引发异常的代码,以便每个人都可以在自己的机器上重现此代码。
标签: c# multithreading visual-studio-2010 infinite-loop unhandled-exception