Cat*_*lMF 2 c# multithreading exception-handling thread-safety
以下示例简化了我的问题.在新线程中抛出异常.如果我不在线程中处理它,它不会被外部try/catch捕获并崩溃我的应用程序.
有没有办法保证我发现任何异常.
try
{
new Thread(delegate()
{
throw new Exception("Bleh"); // <--- This is not caught
}).Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Run Code Online (Sandbox Code Playgroud)
一般来说,最容易捕获线程本身的异常.
但是如果你想从线程函数本身分别捕获异常(如果你可以使用Task而不是旧的Thread方法),你可以编写如下代码:
var task = Task.Factory.StartNew(() =>
{
throw new Exception("Test");
});
task.ContinueWith(t => handleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)
这用于ContinueWith()在第一个线程完成并发生异常后调用另一个方法,因此您可以记录异常或其他:
static void handleException(AggregateException exception)
{
foreach (var ex in exception.Flatten().InnerExceptions)
Console.WriteLine(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
这并不能让你解决任何问题 - 唯一明智的做法是在线程函数本身中正确处理异常.