这是使用Tasks处理AggregateException的错误方法

时间:2015-08-12 13:21:28

标签: c# exception-handling

需要优雅地处理AggregateExceptions。这种方式是否正确?

try
{
    var message = await _queue.ReceiveAsync();
    // rest of code
    //
    var response = await process(body);
}
catch (AggregateException ae)
{
    foreach (var e in ae.InnerExceptions)
    {
         Trace.TraceError(e.Message);
    }
}

2 个答案:

答案 0 :(得分:1)

await展开AggregateException,因此无需执行您正在执行的操作。但是,如果您已完成var response = process(body).Result,那么您的处理将是必要的。

答案 1 :(得分:1)

正如@erikkallen指出的那样,如果您使用AggregateException,则不应该<{1}}。

但是,如果你不是,你就错了。

聚合异常实际上可以是异常的(即,它可以包含其他await,其中包含更多异常等)。因此,您应该使用AggregateExceptions

Flatten

请参阅MSDN上的Attached Child Tasks and Nested AggregateExceptions