3

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Take a look on this article of Jon Skeet: https://codeblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/ – Silviu Antochi Jun 11 '20 at 14:22

1 Answers1

4

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

var completedTask = await Task.WhenAny(persistenceTask, monitorsTask);
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810