views:

75

answers:

1

Is there a shorter way to wait for multiple threads to finish? Maybe using ContinueWhenAll... but I don't want to run the rest of my code async.

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.
+3  A: 

If you replace the for() loop with Parallel.For() or Parallel.ForEach() you don't need a Task list or anything. I'm not sure why you would want a .WaitAll() after a ForEach, doesn't even seem necessary.

The Parallel.loops stop when all Tasks are done.

Henk Holterman
I want to ensure that all the objects are finished processing before continuing with the DoSomeSync calls.
Jeff Meatball Yang
@Jeff: Yes I thought so. A Parallel.For() doesn't need a WaitAll.
Henk Holterman
I see what you mean now - is there some page that documents this? I could not find any.
Jeff Meatball Yang
@Jeff: It's not exactly spelled out, no. But it can be deduced from the description of the aggregate exception and the LoopResult: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopresult_members.aspx
Henk Holterman