Today my colleagues and I discussed how to handle exceptions in C# 5.0 async
methods correctly, and we wondered if awaiting multiple tasks at once also observes the exceptions that do not get unwrapped by the runtime.
Consider the following code snippet:
async Task ExceptionMethodAsync()
{
await Task.Yield();
throw new Exception();
}
async Task CallingMethod()
{
try
{
var a = ExceptionMethodAsync();
var b = ExceptionMethodAsync();
await Task.WhenAll(a, b);
}
catch(Exception ex)
{
// Catches the "first" exception thrown (whatever "first" means)
}
}
What happens to the second task now? Both will be in a faulted state, but is the second task's exception now observed or unobserved?