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?

3
  • Take a look at stackoverflow.com/questions/18314961/… Commented Oct 30, 2019 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? Commented Oct 30, 2019 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 Commented Oct 30, 2019 at 19:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.