With # TPL, how do you know that all tasks are complete?

I have a Loop that generates tasks.

the code:

Task task = null; foreach (Entity a in AAAA) { // create the task task = new Task(() => { myMethod(a); }, Token, TaskCreationOptions.None); task.Start(); } 

As you can see in each iterative task, the object has a new initialization (..new Task (() => ..) How can I find out that all tasks are completed?

+8
c # task-parallel-library task
source share
3 answers

I will replace it with

  Parallel.ForEach(..., () => myMethod(a), ...) 

Then you get an automatic wait for all tasks at the end of ForEach.

And maybe start ForEach from a separate task.

+23
source share
 var allTasks = new List&ltTask&gt(); foreach (Entity a in AAAA) { // create the task task = new Task(() => { myMethod(a); }, Token, TaskCreationOptions.None); // Add the tasks to a list allTasks.Add(task); task.Start(); } // Wait until all tasks are completed. Task.WaitAll(allTasks.ToArray()); 
+12
source share

You will need to maintain links to all tasks created in the loop. Then you can use the Task.WaitAll method (see MSDN link ). You can create an array and assign tasks to the elements of the array (in C # 2.0), or you can use LINQ:

 var tasks = AAAA.Select((Entity a) => Task.Factory.StartNew(() => { myMethod(a); }, Token, TaskCreationOptions.None)).ToArray(); Task.WaitAll(tasks) 

If you don't need to use tasks (explicitly), then Henk's suggestion to use Parallel.ForEach is probably the best option.

+8
source share

All Articles