How to correctly write Parallel.For with async methods

后端 未结 4 762
夕颜
夕颜 2020-12-01 16:13

How would I structure the code below so that the async method gets invoked?

Parallel.For(0, elevations.Count(), delegate(int i)
{
   allSheets.AddRange(await         


        
4条回答
  •  广开言路
    2020-12-01 16:43

    The easiest way to invoke your async method inside Parallel.For is next:

    Parallel.For(0, elevations.Count(), async i =>
    {
       allSheets.AddRange(await BuildSheetsAsync(userID, elevations[i], includeLabels));
    });
    

    ==============

    MarioDS mentioned absolutely right in the comment that in that case you may have unobserved exceptions. And this is definitely very important thing which you should always take in mind then have a deal with async delegates.

    In this case if you think that you will have exceptions you can use try/catch block inside delegate. Or in some cases if your situation is good for it you can subscribe on TaskScheduler.UnobservedTaskException event.

提交回复
热议问题