Parallel.ForEach 是否需要 AsParallel()
ParallelEnumerable
有一个静态成员AsParallel
。如果我有一个 IEnumerable
并且想要使用 Parallel.ForEach
是否意味着我应该始终使用 AsParallel
?
例如 这两者都正确吗(其他条件相同)?
没有 AsParallel
:
List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)), f => list.Add(f));
还是有 AsParallel
?
List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)).AsParallel(), f => list.Add(f));
ParallelEnumerable
has a static member AsParallel
. If I have an IEnumerable<T>
and want to use Parallel.ForEach
does that imply that I should always be using AsParallel
?
e.g.
Are both of these correct (everything else being equal)?
without AsParallel
:
List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)), f => list.Add(f));
or with AsParallel
?
List<string> list = new List<string>();
Parallel.ForEach<string>(GetFileList().Where(file => reader.Match(file)).AsParallel(), f => list.Add(f));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于所称的内容,它们是不同的问题。
.AsParallel()
并行化枚举而不是任务委托。Parallel.ForEach
并行化循环,将任务分配给每个元素的工作线程。因此,除非您的源枚举因并行而获得收益(例如,reader.Match(file) 成本高昂),否则它们是相等的。对于你的最后一个问题,是的,两者都是正确的。
另外,您可能还想了解另一种结构,它可以稍微缩短它,但仍能获得 PLINQ 的最大好处:
It depends on what's being called, they are separate issues.
.AsParallel()
Parallelizes the enumeration not the delegation of tasks.Parallel.ForEach
Parallelized the loop, assigning tasks to worker threads for each element.So unless your source enumeration gains from becoming parallel (e.g.
reader.Match(file)
is expensive), they are equal. To your last question, yes, both are also correct.Also, there's one other construct you may want to look at that shortens it a bit, still getting maximum benefit of PLINQ: