【发布时间】:2018-06-09 06:08:49
【问题描述】:
以下两个代码并行处理列表中的项目,并行度阈值为 5。它们实际上是否相同?
Parallel.ForEach 与 MaxDegreeOfParallelism
public async Task Run()
{
var list = // List<....>
Parallel.ForEach(list,
new ParallelOptions { MaxDegreeOfParallelism = 5}, d => {
....
process(d).RunSynchronously();
....
});
}
使用Partitioner.Create(...).GetPartitions(...)的扩展方法
public async Task Run()
{
var list = // List<....>
await list.ForEachAsync(list.Count() / 5 + 1, async d =>
{
....
await process(d);
....
});
}
public static class Extension
{
public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate {
using (partition)
while (partition.MoveNext())
await body(partition.Current);
}));
}
}
【问题讨论】:
-
第一个向
Parallel.Foreach发送一个异步委托,这会导致一个未等待的异步无效。Parallel.Foreach不适用于异步操作,而仅适用于 CPU 绑定代码。 -
我已经更新了问题并为第一个问题同步调用了异步方法。
-
五个反对者,为什么?