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

Jef*_*ang 4 .net multithreading task-parallel-library

是否有更短的方法等待多个线程完成?也许使用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.
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 12

如果for()Parallel.For()或替换循环,或者Parallel.ForEach()您不需要任务列表或任何东西.我不确定为什么你会想要一个ForEach之后的.WaitAll(),甚至看起来都没有必要.

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

  • 这不完全正确.Parallel.ForEach立即返回并且任务继续运行,而使用AsParallel()扩展确实在所有任务完成后返回. (3认同)