When to use OrderByCompletion (Jon Skeet) vs Parallel.ForEach with async delegates

前端 未结 2 993
孤街浪徒
孤街浪徒 2021-02-06 10:58

Recently Jon Skeet at NDC London spoke about C# 5 async/await and presented the idea of \"ordering by completion\" a list of async tasks. A link http:/

2条回答
  •  囚心锁ツ
    2021-02-06 11:29

    • Don't use Parallel.ForEach to execute async code. Parallel.ForEach doesn't understand async, so your lambda will be turned into async void, which won't work correctly (Parallel.ForEach will return before all work is done; exceptions won't be handled properly; possibly other issues).

    • Use something like ForEachAsync() when you have a collection of objects (not Tasks), you want to perform some async action for each of them and the actions should execute in parallel.

    • Use OrderByCompletion() when you have a collection of Tasks, you want perform some action (asynchronous or not) for the result of each Task, the actions should not execute in parallel and you want to execute the actions based on the order in which the Tasks complete.

提交回复
热议问题