Running multiple async tasks and waiting for them all to complete

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

    Do you want to chain the Tasks, or can they be invoked in a parallel manner?

    For chaining
    Just do something like

    Task.Run(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
    Task.Factory.StartNew(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
    

    and don't forget to check the previous Task instance in each ContinueWith as it might be faulted.

    For the parallel manner
    The most simple method I came across: Parallel.Invoke Otherwise there's Task.WaitAll or you can even use WaitHandles for doing a countdown to zero actions left (wait, there's a new class: CountdownEvent), or ...

提交回复
热议问题