[英]Wpf handling exception throwing by task
我如何处理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);
}
}
}
还是用这种方式处理异常并不常见?
task.ContinueWith(task => {
if (task .Exception != null)
{
//.........
}
},TaskContinuationOptions.OnlyOnFaulted);
在这里看看http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n#handlingExceptions
您可以捕获[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.
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.