异步 Task.WhenAll 超时 [英] Asynchronous Task.WhenAll with timeout

查看:43
本文介绍了异步 Task.WhenAll 超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新的异步 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 将生成的 TaskTask.Delay() 结合起来.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();

这篇关于异步 Task.WhenAll 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆