如何正确书写的Parallel.For与异步方法如何正确、方法、Parallel、For

由网友(一身傲娇气)分享简介:我将如何构建的code以下,这样的异步方法被调用?的Parallel.For(0,elevations.Count(),委托(int i)以{allSheets.AddRange(等待BuildSheetsAsync(用户ID,海拔[I],includeLabels));});解决方案 的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();
 

GraphLab A New Framework For Parallel Machine Learning

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

阅读全文

相关推荐

最新文章