gpt4 book ai didi

c# - Task.WhenAny - 剩余的运行任务会怎样?

转载 作者:IT王子 更新时间:2023-10-29 04:27:55 59 4
gpt4 key购买 nike

我有以下代码:

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。

我的问题是:

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

最佳答案

顺便说一句,我正在阅读Concurrency in C# CookBook , 通过 Stephen Cleary ,我想我可以在这里引用本书的某些部分。

根据秘诀 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.

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 并在第一个任务返回后取消它们的方法。即便如此,前提是这些操作的成本实际上对系统造成了负担。

关于c# - Task.WhenAny - 剩余的运行任务会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426418/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com