我有一个Parallel.ForEach循环,遍历一个集合。在循环内部,我进行多次网络I/O调用。我使用了Task.ContinueWith并嵌套了后续的异步等待调用。处理顺序无关紧要,但每个异步调用中检索的数据应以同步方式处理。这意味着- 对于每个迭代,从第一个异步调用中检索到的数据应传递给第二个异步调用。完成第二个异步调用后,来自两个异步调用的数据应一起被处理。
Parallel.ForEach(someCollection, parallelOptions, async (item, state) =>
{
Task<Country> countryTask = Task.Run(() => GetCountry(item.ID));
//this is my first async call
await countryTask.ContinueWith((countryData) =>
{
countries.Add(countryData.Result);
Task<State> stateTask = Task.Run(() => GetState(countryData.Result.CountryID));
//based on the data I receive in 'stateTask', I make another async call
stateTask.ContinueWith((stateData) =>
{
states.Add(stateData.Result);
// use data from both the async calls pass it to below function for some calculation
// in a synchronized way (for a country, its corresponding state should be passed)
myCollection.ConcurrentAddRange(SomeCalculation(countryData.Result, stateData.Result));
});
});
});
我尝试了上面的方法,但没有使用continue await时无法同步工作。现在,上述代码执行完成,但未处理任何记录。
请问是否有帮助?如果需要更多细节,请告诉我。
await
和ContinueWith
混合在同一代码中似乎非常奇怪,如果已经在线程池上运行,使用Task.Run
也很奇怪......我会查看重构的可能性,但这不仅仅是有点奇怪! - Marc GravellContinueWith
...... 几乎从来不需要再使用它了。 - Marc GravellParallel.ForEach
与async / await
混合使用! - user585968Parallel.ForEach
不支持异步操作。传递的 lambda 表达式是async void
的形式。这个方法会在开始异步操作后立即完成,MaxDegreeOfParallelism
选项也不会被遵守……会有很多问题。仅将此方法用于 CPU 密集型任务。 - Theodor Zoulias