Parallel.ForEach 是否需要 AsParallel()

发布于 2024-08-21 20:32:12 字数 663 浏览 6 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心安伴我暖 2024-08-28 20:32:12

这取决于所称的内容,它们是不同的问题。

.AsParallel() 并行化枚举而不是任务委托。

Parallel.ForEach 并行化循环,将任务分配给每个元素的工作线程。

因此,除非您的源枚举因并行而获得收益(例如,reader.Match(file) 成本高昂),否则它们是相等的。对于你的最后一个问题,是的,两者都是正确的。

另外,您可能还想了解另一种结构,它可以稍微缩短它,但仍能获得 PLINQ 的最大好处:

GetFileList().Where(file => reader.Match(file)).ForAll(f => list.Add(f));

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:

GetFileList().Where(file => reader.Match(file)).ForAll(f => list.Add(f));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文