[英]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.