Async Task.WhenAll with timeout

后端 未结 11 2041
梦谈多话
梦谈多话 2020-11-29 04:33

Is there a way in the new async dotnet 4.5 library to set a timeout on the Task.WhenAll method. I want to fetch several sources and stop after say 5 seconds and

11条回答
  •  醉梦人生
    2020-11-29 04:50

    void result version of @i3arnon 's answer, along with comments and changing first argument to use extension this.

    I've also got a forwarding method specifying timeout as an int using TimeSpan.FromMilliseconds(millisecondsTimeout) to match other Task methods.

    public static async Task WhenAll(this IEnumerable tasks, TimeSpan timeout)
    {
      // Create a timeout task.
      var timeoutTask = Task.Delay(timeout);
    
      // Get the completed tasks made up of...
      var completedTasks =
      (
        // ...all tasks specified
        await Task.WhenAll(tasks
    
        // Now finish when its task has finished or the timeout task finishes
        .Select(task => Task.WhenAny(task, timeoutTask)))
      )
      // ...but not the timeout task
      .Where(task => task != timeoutTask);
    
      // And wait for the internal WhenAll to complete.
      await Task.WhenAll(completedTasks);
    }
    

提交回复
热议问题