1、應用ContineWith
var task1 = Task.Run(() => { throw new Exception("task1 faulted."); }).ContinueWith(
t =>
{
Console.WriteLine("{0}: {1}",
t.Exception.InnerException.GetType().Name,
t.Exception.InnerException.Message);
},
TaskContinuationOptions.OnlyOnFaulted); Thread.Sleep(500);
var testTask = TestAsync(5, -10);
testTask.ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine(task.Exception.GetBaseException());
}
else
{
Console.WriteLine(task.Result);
}
});
2、應用Wait
try
{
Task t1 = Task.Factory.StartNew(() => {
throw new Exception("執行失敗");
});
//主線程等待,可以 捕捉異常
t1.Wait();
}
catch (AggregateException ex)
{
foreach (var item in ex.InnerExceptions)
{
Console.WriteLine("異常類型:{0}{1}來自: {2} {3} 異常內容:{4} ", item.GetType(),
Environment.NewLine, item.Source,
Environment.NewLine, item.Message);
}
Console.Write(ex.Message);
}
參考連接: