//AggregateException:是一个异常集合,因为Task中可能抛出异常,所以我们需要新的类型来收集异常对象 static void Method11() { var task = Task.Factory.StartNew(() => { var childTask1 = Task.Factory.StartNew(() => { //实际开发中这个地方写你处理的业务,可能会发生异常.... //自己模拟一个异常 throw new Exception("my god!Exception from childTask1 happend!"); }, TaskCreationOptions.AttachedToParent); var childTask2 = Task.Factory.StartNew(() => { throw new Exception("my god!Exception from childTask2 happend!"); }, TaskCreationOptions.AttachedToParent); }); try { try { task.Wait(); //1.异常抛出的时机 } catch (AggregateException ex) //2.异常所在位置 { foreach (var item in ex.InnerExceptions) { Console.WriteLine(item.InnerException.Message + " " + item.GetType().Name); } //3.异常集合,如果你想往上抛,需要使用Handle方法处理一下 ex.Handle(p => { if (p.InnerException.Message == "my god!Exception from childTask1 happend!") return true; else return false; //返回false表示往上继续抛出异常 }); } } catch (Exception ex) { Console.WriteLine("-----------------------------------------------------"); Console.WriteLine(ex.InnerException.InnerException.Message); } }
标签:Exception,Task,ex,AggregateException,var,异常 From: https://www.cnblogs.com/itjeff/p/16914967.html