且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我想等待抛出 AggregateException,而不仅仅是第一个异常

更新时间:2021-09-11 23:21:19

我不同意你的问题标题中暗示的 await 的行为是不受欢迎的.这在绝大多数情况下都是有意义的.在 WhenAll 情况下,您真的多久需要知道所有的错误详细信息,而不是一个?

I disagree with the implication in your question title that await's behavior is undesired. It makes sense in the vast majority of scenarios. In a WhenAll situation, how often do you really need to know all of the error details, as opposed to just one?

AggregateException 的主要困难在于异常处理,即您失去了捕获特定类型的能力.

The main difficulty with AggregateException is the exception handling, i.e., you lose the ability to catch a particular type.

也就是说,您可以使用扩展方法获得所需的行为:

That said, you can get the behavior you want with an extension method:

public static async Task WithAggregateException(this Task source)
{
  try
  {
    await source.ConfigureAwait(false);
  }
  catch
  {
    // source.Exception may be null if the task was canceled.
    if (source.Exception == null)
      throw;

    // EDI preserves the original exception's stack trace, if any.
    ExceptionDispatchInfo.Capture(source.Exception).Throw();
  }
}