【C#】52. 使用Flatten方法处理并行任务抛出的异常

来源:互联网 发布:手机上淘宝网怎么付款 编辑:程序博客网 时间:2024/06/03 16:21

本篇主要讨论一下InnerException的处理方法flatten。

async static Task<string> GetInfoAsync(string name, int seconds){await Task.Delay(TimeSpan.FromSeconds(seconds));throw new Exception(string.Format("Boom from {0}!", name));}

1、先看一下单个错误的情况,这个比较简单,不存在嵌套异常。

async static Task AsynchronousProcessing(){Console.WriteLine("1. Single exception");try{string result = await GetInfoAsync("Task 1", 2);Console.WriteLine(result);}catch (Exception ex){Console.WriteLine("Exception details: {0}", ex);}}


2、对于并行任务仍然使用上述Try Catch只能捕获第一个异常错误,而不是全部错误。

Console.WriteLine("2. Multiple exceptions");Task<string> t1 = GetInfoAsync("Task 1", 3);Task<string> t2 = GetInfoAsync("Task 2", 2);try{string[] results = await Task.WhenAll(t1, t2);Console.WriteLine(results.Length);}catch (Exception ex){Console.WriteLine("Exception details: {0}", ex);}



3、最后是正确的处理方法,要在catch中对InnerException进行Flatten处理

Console.WriteLine("2. Multiple exceptions with AggregateException");var t1 = GetInfoAsync("Task 1", 3);var t2 = GetInfoAsync("Task 2", 2);Task<string[]> t3 = Task.WhenAll(t1, t2);try{string[] results = await t3;Console.WriteLine(results.Length);}catch{var ae = t3.Exception.Flatten(); //这句话是关键!var exceptions = ae.InnerExceptions;Console.WriteLine("Exceptions caught: {0}", exceptions.Count);foreach (var e in exceptions){Console.WriteLine("Exception details: {0}", e);Console.WriteLine();}}


0 0