您的位置:首页 > 编程语言 > C#

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

2016-12-12 22:20 525 查看
本篇主要讨论一下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# 异常 await 多线程