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

查看:364
本文介绍了异步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.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();

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

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