异步Task.WhenAll与超时Task、WhenAll

2023-09-02 01:46:03 作者:葵一般的少年

有没有办法在新的异步DOTNET 4.5库设置在 Task.WhenAll 方法超时。我想取几个来源,并停止后说,5秒跳到了未完成的来源。

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 skip the sources that weren't finished.

推荐答案

您可以结合所产生的工作 Task.Delay()使用 Task.WhenAny()

You could combine the resulting Task with a Task.Delay() using Task.WhenAny():

await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(timeout));

如果你想收获已完成的任务在发生超时:

If you want to harvest completed tasks in case of a timeout:

var completedResults =
  tasks
  .Where(t => t.Status == TaskStatus.RanToCompletion)
  .Select(t => t.Result)
  .ToList();
 
精彩推荐
图片推荐