Task.WhenAny - 剩余的运行任务会发生什么? [英] Task.WhenAny - What happens with remaining running tasks?

查看:27
本文介绍了Task.WhenAny - 剩余的运行任务会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

List<Task<bool>> tasks = tasksQuery.ToList();
while (tasks.Any())
{
    Task<bool> completedTask = await Task.WhenAny(tasks);
    if (await completedTask)
        return true;

    tasks.Remove(completedTask);
}

它并行启动任务.当第一个完成的任务返回 true 时,该方法返回 true.

It launches tasks in parallel. When first completed task returns true, the method returns true.

我的问题是:

  1. 所有剩余的已启动且可能仍在后台运行的任务会发生什么情况?
  2. 这是执行异步、并行并应在第一个条件发生后返回的代码的正确方法,还是最好逐个启动它们并单独等待?

推荐答案

顺便说一句,我只是在看C# CookBook 中的并发,作者 Stephen Cleary,我我想可以在这里参考本书的某些部分.

Incidentally, I am just reading Concurrency in C# CookBook, by Stephen Cleary, and I can refer to some parts of the book here, I guess.

方法 2.5 - 讨论,我们有

当第一个任务完成后,考虑是否取消剩余的任务.如果其他任务没有被取消但也从未被等待,则它们将被放弃.放弃的任务将一直运行到完成,其结果将被忽略.那些被放弃的任务的任何异常也将被忽略.

When the first task completes, consider whether to cancel the remaining tasks. If the other tasks are not canceled but are also never awaited, then they are abandoned. Abandoned tasks will run to completion, and their results will be ignored. Any exceptions from those abandoned tasks will also be ignored.

Task.WhenAny 的另一个反模式是在任务完成时对其进行处理.乍一看,保留任务列表并在任务完成时从列表中删除每个任务似乎是一种合理的方法.这种方法的问题在于,当存在 O(N) 算法时,它的执行时间为 O(N^2).

Another antipattern for Task.WhenAny is handling tasks as they complete. At first it seems like a reasonable approach to keep a list of tasks and remove each task from the list as it completes. The problem with this approach is that it executes in O(N^2) time, when an O(N) algorithm exists.

除此之外,我认为 WhenAny 肯定是正确的方法.只需考虑以下 Leonid 方法,为所有任务传递相同的 CancellationToken 并取消它们第一个回来后.即便如此,前提是这些操作的成本实际上对系统造成了负担.

Besides that, I think WhenAny is surely the right approach. Just consider the following Leonid approach of passing the same CancellationToken for all tasks and cancel them after the first one returns. And even that, only if the cost of these operations is actually taxing the system.

这篇关于Task.WhenAny - 剩余的运行任务会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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