如何正确书写的Parallel.For与异步方法 [英] How to correctly write Parallel.For with async methods

查看:443
本文介绍了如何正确书写的Parallel.For与异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何构建的code以下,这样的异步方法被调用?

 的Parallel.For(0,elevations.Count(),委托(int i)以
{
   allSheets.AddRange(等待BuildSheetsAsync(用户ID,海拔[I],includeLabels));
});
 

解决方案

的Parallel.For()不与正常工作异步的方法。如果您不需要限制并行度(即你没事了所有的在同一时间执行的任务),你可以简单地启动所有工作 S和然后等待它们完成:

  VAR任务= Enumerable.Range(0,elevations.Count())
    。选择(I => BuildSheetsAsync(用户ID,海拔[I],includeLabels));
名单<位图> allSheets =(等待Task.WhenAll(任务))的SelectMany(X => X)。.ToList();
 

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 BuildSheetsAsync(userID, elevations[i], includeLabels));
});

解决方案

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();

这篇关于如何正确书写的Parallel.For与异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆