Bor*_*rka 4 .net multithreading threadabortexception
我正在使用 .NET 1.1 兼容模式进行未处理的异常处理。问题是,当 LegacyUnhandledExceptionPolicy 设置为“1”(这是我想要的)时,我无法捕获并吞下 ThreadAbortException。
示例代码:
应用程序配置:
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
</configuration>
Run Code Online (Sandbox Code Playgroud)
代码:
class Program {
static void Main(string[] args) {
AppDomain.CurrentDomain.UnhandledException += _onBackgroundThreadCrash;
var t = new Thread(_worker) { IsBackground = true };
t.Start();
Thread.Sleep(1000);
t.Abort();
Console.ReadLine();
}
private static void _worker() {
try {
while (true);
} catch (ThreadAbortException) {
// expected thread exit, don't rethrow
}
}
private static void _onBackgroundThreadCrash(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject as Exception);
}
}
Run Code Online (Sandbox Code Playgroud)
当遗留异常处理为“0”(OFF)时,上面的代码会如预期的那样安静地吞下 ThreadAbortException。
但是,当遗留异常处理为“1”时,上面的代码将 ThreadAbortException 打印到控制台,这不是我所期望的。
有任何想法吗?
谢谢。
您无法捕获 ThreadAbortException,它总是在捕获后重新引发。您的问题有两种基本解决方案。
第一个是您重置中止请求:
catch (ThreadAbortException) {
// expected thread abort request, reset it and exit thread
Thread.ResetAbort();
}
Run Code Online (Sandbox Code Playgroud)
第二个是解决启用遗留异常处理时发生的另一件事。现在还针对非致命异常引发 AppDomain.UnhandledException 事件。像这样编写您的异常处理程序:
private static void _onBackgroundThreadCrash(object sender, UnhandledExceptionEventArgs e) {
if (e.IsTerminating) {
Console.WriteLine(e.ExceptionObject as Exception);
}
}
Run Code Online (Sandbox Code Playgroud)
我不得不推荐第一个解决方案,您真的不希望终止线程的未处理异常根本不留下任何痕迹。