【C#】52. 使用Flatten方法处理并行任务抛出的异常
2016-12-12 22:20
525 查看
本篇主要讨论一下InnerException的处理方法flatten。
1、先看一下单个错误的情况,这个比较简单,不存在嵌套异常。
2、对于并行任务仍然使用上述Try Catch只能捕获第一个异常错误,而不是全部错误。
3、最后是正确的处理方法,要在catch中对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(); } }
相关文章推荐
- C#中异常的处理方法 try{} eatch{} finally{} 的使用
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- C#读取WORD时发生“拒绝访问”及“消息筛选器显示应用程序正在使用中”异常的处理
- C#中使用lockbits方法处理图像(译文)
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- 使用C#进行图像处理的几种方法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法 (转)
- C# 如何处理抛出的异常,或者已知的错误
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- C#中使用Split分割字符串后,空格处理方法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- [转]使用C#进行图像处理的几种方法
- C# 如何处理抛出的异常,或者已知的错误
- [转]使用C#进行图像处理的几种方法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- 使用ASP.NET AJAX异步调用Web Service和页面中的类方法(2):处理异步调用中的异常
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- WinCE中使用C#时使用WndProc方法的处理