Running multiple async tasks and waiting for them all to complete

后端 未结 9 1677
渐次进展
渐次进展 2020-11-22 13:36

I need to run multiple async tasks in a console application, and wait for them all to complete before further processing.

There\'s many articles out there, but I see

9条回答
  •  盖世英雄少女心
    2020-11-22 14:22

    This is how I do it with an array Func<>:

    var tasks = new Func[]
    {
       () => myAsyncWork1(),
       () => myAsyncWork2(),
       () => myAsyncWork3()
    };
    
    await Task.WhenAll(tasks.Select(task => task()).ToArray()); //Async    
    Task.WaitAll(tasks.Select(task => task()).ToArray()); //Or use WaitAll for Sync
    

提交回复
热议问题