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);
}
参考连接:
https://www.cnblogs.com/tianma3798/p/7003862.html
https://www.cnblogs.com/Johar/p/9245029.html