4

是否有更短的方法来等待多个线程完成?也许使用 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.
4

1 回答 1

12

如果您将for()循环替换为Parallel.For()或者Parallel.ForEach()您不需要任务列表或任何东西。我不确定为什么你会在 ForEach 之后想要一个 .WaitAll(),这似乎没有必要。

所有任务完成后并行循环停止。

于 2010-09-08T15:15:33.813 回答