Running multiple async tasks and waiting for them all to complete

后端 未结 9 1492
渐次进展
渐次进展 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:28

    You can use WhenAll which will return an awaitable Task or WaitAll which has no return type and will block further code execution simular to Thread.Sleep until all tasks are completed, canceled or faulted.

    Example

    var tasks = new Task[] {
        TaskOperationOne(),
        TaskOperationTwo()
    };
    
    Task.WaitAll(tasks);
    // or
    await Task.WhenAll(tasks);
    

    If you want to run the tasks in a praticular order you can get inspiration form this anwser.

提交回复
热议问题