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

前端 未结 2 994
孤街浪徒
孤街浪徒 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:27

    Parallel.ForEach(myCollection, async item =>
    

    This is almost certainly not what you want. The delegate has type Action, and so the anonymous method is an async void method. That means it gets launched, and you have no way of checking its status other than by checking for any of its side effects. In particular, if anything goes wrong, you cannot catch and handle the exception.

    Assuming nothing goes wrong, though, results will be added to bag as they complete. Until anything completes, bag will be empty.

    In contrast, OrderByCompletion returns an IEnumerable> that immediately contains all not-yet-finished tasks. You could await the fifth element and continue when any five tasks have completed. This might be useful when, for example, you want to run a large number of tasks and periodically update a form to show the progress.

    The third option you gave, ForEachAsync, would behave like ForEach, except it would do it right, without the problems mentioned above.

提交回复
热议问题