I want await to throw AggregateException, not just the first Exception

前端 未结 4 1304
滥情空心
滥情空心 2020-11-28 09:15

When awaiting a faulted task (one that has an exception set), await will rethrow the stored exception. If the stored exception is an AggregateException

4条回答
  •  情深已故
    2020-11-28 10:10

    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?

    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();
      }
    }
    

提交回复
热议问题