直接上代码:只有加入wait才能捕获异常,不然就没有,这个比较鸡肋。本质没有wait,主线程和子线程就没有关系了,也就捕获不到子线程异常了
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1.TaskTest { public class TaskTryCatch { public void Run() { try { var task = Task.Run(() => { int a = 0; int i = 1 / a; }); //只有加入wait才能捕获异常,不然就没有 Task.WaitAll(new Task[] { task }); } catch (AggregateException ex) { Console.WriteLine(ex.Message); } } } }