0

Reading book a concurrency C# which says when Task.WhenAll is awaited, only one exception is trhown if multiple exceptions are thrown from each task in Task.WhenAll

Bit confised as Ive seen sample code below which suggests all exceptions are captured in the AggregateException and not just ONE thrown?

Task allTasks = Task.WhenAll(task1, task2);
  try
  {
    await allTasks;
  }
  catch
  {
    AggregateException allExceptions = allTasks.Exception;
    ...
  }

whereas the below only expects one exception to be thrown

Well the code below says it will only throw one of the excpetions from the book which is confusing

var task1 = ThrowNotImplementedExceptionAsync();
  var task2 = ThrowInvalidOperationExceptionAsync();

  try
  {
    await Task.WhenAll(task1, task2);
  }
  catch (Exception ex)
  {
    // "ex" is either NotImplementedException or InvalidOperationException.
    ...
  }
TheWommies
  • 4,922
  • 11
  • 61
  • 79
  • Maybe they mean that the only thrown exception is the aggregate exception? – Hans Kilian Nov 02 '20 at 09:09
  • 1
    All exceptions are wrapped inside the `AggregateException`, because it is impossible to throw multiple exceptions. – Silvermind Nov 02 '20 at 09:15
  • 1
    So run the code in question and see what happens. Then you'll know which one is right. – Servy Nov 02 '20 at 18:09
  • _"the code below says it will only throw one of the excpetions from the book which is confusing"_ -- why is it confusing? The two code examples are not equivalent. The first is not looking at the exception that was thrown, but rather the exception in the `Task` object that `WhenAll()` returned. The second is looking at the exception that was thrown. The two examples are not inconsistent with each other, nor even mutually exclusive. See duplicate for detailed discussion of dealing with `AggregateException` and `WhenAll()`. – Peter Duniho Nov 02 '20 at 19:06
  • See also relevant Q&A such as https://stackoverflow.com/questions/48687177/handling-multiple-exceptions-from-async-parallel-tasks and https://stackoverflow.com/questions/36455666/why-does-aggregateexception-thrown-from-gui-thread-get-unwrapped-in-app-except (not dupes, but still useful and possibly pertinent to your scenario) – Peter Duniho Nov 02 '20 at 19:08

0 Answers0