我如何处理在工作线程中抛出的wpf的异常?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
var task = Task.Factory.StartNew(() =>
{
Debug.WriteLine("Hello");
throw new Exception();
});
try
{
task.Wait();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
或者以这种方式处理异常并不常见?
答案 0 :(得分:2)
task.ContinueWith(task => {
if (task .Exception != null)
{
//.........
}
},TaskContinuationOptions.OnlyOnFaulted);
看看http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n#handlingExceptions
答案 1 :(得分:0)
您可以抓住[System.AggregateException]
来检查您是否可以处理任何InnerExceptions。请参阅下面的示例。
var task = Task.Factory.StartNew(() =>
{
Debug.WriteLine("Hello");
throw new InvalidOperationException(); // throw an InvalidOperationException that is handled.
});
try
{
task.Wait();
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is InvalidOperationException) // We know how to handle this exception.
{
Console.WriteLine("InvalidOperationException error.");
return true; // Continue with operation.
}
return false; // Let anything else stop the application.
});
}