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

最后都变了- 提交于 2019-12-20 13:33:13

问题


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?


回答1:


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.




回答2:


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());



回答3:


You'll need to keep references to all the tasks created in the loop. Then you can use the Task.WaitAll method (see MSDN reference). You can either create an array and assign tasks to 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 a better option.



来源:https://stackoverflow.com/questions/5067412/c-sharp-tpl-how-to-know-that-all-tasks-are-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!