The article is wrong. When you run your code, the await
ed Task
contains an exception that looks something like this:
AggregateException
AggregateException
NullReferenceException
AggregateException
ArgumentException
What await
(or, more specifically, TaskAwaiter.GetResult()
) does here is that it takes the outer AggregateException
and rethrows its first child exception. Here, that's another AggregateException
, so that's what is thrown.
Example of code where a Task
has multiple exceptions and one of them is directly rethrown after await
would be to use Task.WhenAll()
instead of AttachedToParent
:
try
{
await Task.WhenAll(
Task.Factory.StartNew(() => { throw new NullReferenceException(); }),
Task.Factory.StartNew(() => { throw new ArgumentException(); }));
}
catch (AggregateException ex)
{
// this catch will never be target
Console.WriteLine("** {0} **", ex.GetType().Name);
}
catch (Exception ex)
{
Console.WriteLine("## {0} ##", ex.GetType().Name);
}