gpt4 book ai didi

.net - 使用 .NET 4.0 中的任务并行库等待所有任务完成

转载 作者:行者123 更新时间:2023-12-03 06:32:03 26 4
gpt4 key购买 nike

是否有更短的方法来等待多个线程完成?也许使用ContinueWhenAll...但我不想异步运行其余的代码。

List<object> objList = // something

List<Task> taskHandles = new List<Task>();
for(int i = 0; i < objList.Count; i++) {

taskHandles.Add(Task.Factory.StartNew(() => { Process(objList[i]); }));

}

foreach(Task t in taskHandles) { t.Wait(); }

DoSomeSync1();
..
DoSomeSync2();
..
DoSomeSync3();
..

// I could have used ContinueWhenAll(waitHandles, (antecedent) => { DoSomeSync...; });
// but I'd rather not have to do that.
// It would be nice if I could have just done:

Parallel.ForEach(objList, (obj) => { Process(obj); }).WaitAll();

// or something like that.

最佳答案

如果将 for() 循环替换为 Parallel.For()Parallel.ForEach(),则不需要任务 list 什么的。我不知道为什么你会在 ForEach 之后想要一个 .WaitAll() ,甚至似乎没有必要。

当所有任务完成时,并行循环停止。

关于.net - 使用 .NET 4.0 中的任务并行库等待所有任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669188/

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