C# aggregateexception flatten innerexceptions

static void AggregateExceptionsDemo()
        {
            var task1 = Task.Factory.StartNew(() =>
              {
                  var child1 = Task.Factory.StartNew(() =>
                  {
                      throw new CustomException("Attached child2 faulted.");

                  },TaskCreationOptions.AttachedToParent);
                  throw new CustomException("Attached child1 faulted.");
              },TaskCreationOptions.AttachedToParent);

            try
            {
                task1.Wait();
            }
            catch(AggregateException aes)
            {
                foreach(var e in aes.Flatten().InnerExceptions)
                {
                    if(e is CustomException)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
posted @ 2020-01-19 23:38  FredGrit  阅读(298)  评论(0编辑  收藏  举报