4

I am probably missing a very obvious fact, but I have a hard time understanding the need for AggregatedExceptions.

I know since async/await we don't have to bother with AggregatedExceptions anymore (or at least are confronted with them less frequently). I can relate to that, because I simply start a task and at some time I choose to synchronize the 'calling thread' with the 'task which runs in parallel'

var sometTask = DoSomethingInParallelAsync().ConfigureAwait(false);
...
...
await someTask;

In this scenario, an exception that occurred in DoSomethingInParallelAsync() will be presented to me when I await that call.

Why is that so different without using await, but Wait on the Task explicitly?

var someTask = DoSomethingInParallelAsync();
...
...
someTask.Wait();

An exception thrown in this example, will always wrap the thrown Exception in an AggregateException. I still don't understand why.

What can't I do when using async/await which takes away the need for AggregateExceptions?

bas
  • 13,550
  • 20
  • 69
  • 146
  • Take a look at https://stackoverflow.com/questions/18314961/i-want-await-to-throw-aggregateexception-not-just-the-first-exception – Sean Oct 30 '19 at 13:59
  • Hi @Sean, thanks for the link. Still puzzled though. In the example presented below I understand that multiple exceptions can occur on different threads / tasks in parallel. But in my question, I simply start 1 task, and wait for it. That wouldn't produce multiple exceptions on the `Task.Wait` call. So why is it still wrapped in the `AggregateException`? – bas Oct 30 '19 at 19:32
  • Not sure if I make myself clear. I would understand that `Task.WhenAll` would throw an `AggregateException`, I don't understand why `Task.Wait` would throw an `AggregateException` – bas Oct 30 '19 at 19:34

1 Answers1

0

Causing and handling the error

Task task1 = Task.Factory.StartNew(() => { throw new ArgumentException(); } );
Task task2 = Task.Factory.StartNew(() => { throw new UnauthorizedAccessException(); } );

try
{
    Task.WaitAll(task1, task2);
}
catch (AggregateException ae)
{
}

and also see that links

here is an example : link2

Fahim Akhtar
  • 359
  • 1
  • 4
  • 13
  • OK, that does explain why the `AggregateException` exists. But that does not really explain to me why the `Task.Wait` call would wrap the exception in a `AggregateException`. In what scenario would you be able to produce more than one exception on a single task? It's just one task, with one result, right? Failed with an exception or completed successfully. PS: I also don't understand who downvoted your answer either ... – bas Oct 30 '19 at 19:28