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

前端 未结 3 865
失恋的感觉
失恋的感觉 2021-02-06 07:16

I have the Loop which generates tasks.

Code:

Task task = null;
foreach (Entity a in AAAA)
{
  // create the task 
  task = new Task(() => {
    myMeth         


        
3条回答
  •  野性不改
    2021-02-06 07:54

    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.

提交回复
热议问题