Await for list of Tasks

后端 未结 2 1903
轮回少年
轮回少年 2020-12-14 15:07

I\'m trying to do something like this:

foreach (var o in ObjectList) 
{ 
    CalculateIfNeedToMakeTaskForO(o);

    if (yes) 
        TaskList.Add(OTaskAsync         


        
2条回答
  •  半阙折子戏
    2020-12-14 15:35

    You are looking for Task.WaitAll (assuming your TaskList implemented IEnumerable)

    Task.WaitAll(TaskList.ToArray());
    

    Edit: Since WaitAll only takes an array of task (or a list of Task in the form of a variable argument array), you have to convert your Enumerable. If you want an extension method, you can do something like this:

    public static void WaitAll(this IEnumerable tasks) 
    {
        Task.WaitAll(tasks.ToArray());
    }      
    
    TaskList.WaitAll();
    

    But that's really only syntactic sugar.

提交回复
热议问题