如何使用异步方法正确编写 Parallel.For [英] How to correctly write Parallel.For with async methods

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

问题描述

我将如何构建下面的代码以便调用异步方法?

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() 不适用于 async 方法.如果您不需要限制并行度(即您可以同时执行所有任务),您可以简单地启动所有Task然后等待它们完成:

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天全站免登陆