Why is awaiting on this faulted task not throwing the exception?

Viewed 187

I thought I'd got my head around exceptions in async methods, and WhenAll/WhenAny behaviour when tasks throw exceptions, but:

internal async Task RunAsync()
{
    //...

    //one of persistenceTask, monitorsTask is going to throw an exeption
    var completedTask = Task.WhenAny(persistenceTask, monitorsTask);

    await completedTask; //I expect this to throw but it doesn't
}

.

//in a calling method later
var t = await RunAsync();

When completedTask has status faulted, I can see the inner exception in the debugger, but t ends up as successfully completed. What I want is the exception to get thrown by RunAsync - I know WhenAny does not throw if a task faults, but I thought if I await on a faulted task (completedTask) this would throw.

What am I getting wrong?

1 Answers

WhenAny returns a task that never fails. The result of that task is the completed task.

var completedTask = await Task.WhenAny(persistenceTask, monitorsTask);
Related