任务中处理AggregateException的方式是否有误?

3
需要优雅地处理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个回答

2
正如@erikkallen所指出的,如果您使用await,则不应该出现AggregateException。但是,如果您没有使用它,那么您将处理错误。聚合异常实际上可以是异常树(即,它可以包含其他AggregateExceptions,这些异常又包含更多的异常等)。因此,您应该使用Flatten:
foreach (var e in ae.Flatten().InnerExceptions)

请参考MSDN上的附加的子任务和嵌套的AggregateExceptions


1

await 可以解开 AggregateException,所以你不需要做你正在做的事情。但是,如果你已经执行了 var response = process(body).Result,那么你的处理是必要的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接