How to correctly write Parallel.For with async methods

后端 未结 4 747
夕颜
夕颜 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:39

    Parallel.For() doesn't work well with async methods. If you don't need to limit the degree of parallelism (i.e. you're okay with all of the tasks executing at the same time), you can simply start all the Tasks and then wait for them to complete:

    var tasks = Enumerable.Range(0, elevations.Count())
        .Select(i => BuildSheetsAsync(userID, elevations[i], includeLabels));
    List allSheets = (await Task.WhenAll(tasks)).SelectMany(x => x).ToList();
    

提交回复
热议问题