Why does the Task.WhenAny not throw an expected TimeoutException?

前端 未结 1 500
闹比i
闹比i 2020-12-07 00:48

Please, observe the following trivial code:

class Program
{
    static void Main()
    {
        var sw = new Stopwatch();
        sw.Start();
        try
           


        
相关标签:
1条回答
  • 2020-12-07 01:32

    Task.WhenAny doesn't rethrow exceptions from the individual tasks (unlike Task.WhenAll):

    "The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state."

    From Task.WhenAny

    That means that it will complete successfully no matter what without any type of exceptions.

    To actually rethrow the exception of the individual completed task you need to await the returned task itself:

    var completedTask = await Task.WhenAny(tasks); // no exception
    await completedTask; // possible exception
    

    Or in your case:

    Task.WhenAny(RunAsync()).GetAwaiter().GetResult().GetAwaiter().GetResult();
    
    0 讨论(0)
提交回复
热议问题