Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# TPL how to know that all tasks are done?

I have the Loop which generates tasks.

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 iteration task object has new initialization (..new Task(() =>..) How can I know that all tasks done?

like image 276
Yara Avatar asked Feb 21 '11 14:02

Yara


2 Answers

I f you replace this with a

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

Then you get an automatic Wait on all tasks at the end of the ForEach.

And maybe run the ForEach from a separate Task.

like image 188
Henk Holterman Avatar answered Sep 19 '22 02:09

Henk Holterman


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());
like image 45
Software.Developer Avatar answered Sep 20 '22 02:09

Software.Developer