gpt4 book ai didi

c# - 如何使用 Task.WaitAny() 确定哪些任务首先完成?

转载 作者:行者123 更新时间:2023-11-30 15:51:13 30 4
gpt4 key购买 nike

在这段代码中,您总是会得到相同的结果。不知道为什么这些任务的ID是1,3,4。

如果您在 int index = Task.WaitAny(tasks); 处放置一个断点并等待 2 秒,您将获得良好的结果。第一种情况的结果不同,ID 等于 1、2、3。

public class Example
{
public static void Main()
{
var tasks = new Task[3];
var rnd = new Random();
for (int ctr = 0; ctr <= 2; ctr++)
tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

try
{
int index = Task.WaitAny(tasks);
Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
Console.WriteLine("Status of all tasks:");

foreach (var t in tasks)
Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status);
}
catch (AggregateException)
{
Console.WriteLine("An exception occurred.");
}
}
}

// The example displays output like the following:
// Task #1 completed first.
//
// Status of all tasks:
// Task #3: Running
// Task #1: RanToCompletion
// Task #4: Running

最佳答案

如果您查看 documentation Task.Id,它说:

Task IDs are assigned on-demand and do not necessarily represent the order in which task instances are created. Note that although collisions are very rare, task identifiers are not guaranteed to be unique.

(强调我的)

因此,为此目的使用 Task.Id(即检查首先完成的任务)绝不可靠。您应该做的是改为依赖数组中元素的索引。在这种情况下,您的代码将如下所示:

var tasks = new Task[3];
var rnd = new Random();
for (int ctr = 0; ctr <= 2; ctr++)
tasks[ctr] = Task.Run(() => Thread.Sleep(rnd.Next(500, 3000)));

try
{
int index = Task.WaitAny(tasks);
Console.WriteLine("Task #{0} completed first.\n", (index + 1));
Console.WriteLine("Status of all tasks:");

for (int i = 0; i <= 2; i++)
Console.WriteLine(" Task #{0}: {1}", (i + 1), tasks[i].Status);
}
catch (AggregateException)
{
Console.WriteLine("An exception occurred.");
}

这样,当您多次运行该程序时,您会得到不同的结果。你可以try it online .

有关Task.Id 行为的更多信息,您可以阅读Stephen Cleary的文章:A Few Words on Task.Id (and TaskScheduler.Id) .

关于c# - 如何使用 Task.WaitAny() 确定哪些任务首先完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685499/

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