对于每个正常的foreach使用parallel.foreach循环是否有意义?
我什么时候应该开始使用parallel.foreach,只迭代1,000,000个项目?
我有这样的方法:
public async Task<MyResult> GetResult()
{
MyResult result = new MyResult();
foreach(var method in Methods)
{
string json = await Process(method);
result.Prop1 = PopulateProp1(json);
result.Prop2 = PopulateProp2(json);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后我决定使用Parallel.ForEach:
public async Task<MyResult> GetResult()
{
MyResult result = new MyResult();
Parallel.ForEach(Methods, async method =>
{
string json = await Process(method);
result.Prop1 = PopulateProp1(json);
result.Prop2 = PopulateProp2(json);
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
但现在我有一个错误:
在异步操作仍处于挂起状态时完成异步模块或处理程序.
我将如何构造下面的代码,以便调用异步方法?
Parallel.For(0, elevations.Count(), delegate(int i)
{
allSheets.AddRange(await BuildSheetsAsync(userID, elevations[i], includeLabels));
});
Run Code Online (Sandbox Code Playgroud)