How to correctly write Parallel.For with async methods

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<Bitmap> allSheets = (await Task.WhenAll(tasks)).SelectMany(x => x).ToList();

Leave a Comment