C#:AsParallel - 顺序重要吗?
我正在构建一个简单的 LinQ 到对象查询,我想对其进行并行化,但是我想知道语句的顺序是否重要?
例如
IList<RepeaterItem> items;
var result = items
.Select(item => item.FindControl("somecontrol"))
.Where(ctrl => SomeCheck(ctrl))
.AsParallel();
vs.
var result = items
.AsParallel()
.Select(item => item.FindControl("somecontrol"))
.Where(ctrl => SomeCheck(ctrl));
有什么区别吗?
I'm building a simple LinQ-to-object query which I'd like to parallelize, however I'm wondering if the order of statements matter ?
e.g.
IList<RepeaterItem> items;
var result = items
.Select(item => item.FindControl("somecontrol"))
.Where(ctrl => SomeCheck(ctrl))
.AsParallel();
vs.
var result = items
.AsParallel()
.Select(item => item.FindControl("somecontrol"))
.Where(ctrl => SomeCheck(ctrl));
Would there be any difference ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
绝对地。在第一种情况下,投影和过滤将串行完成,只有然后才会并行化。
在第二种情况下,投影和过滤将并行发生。
除非您有特殊原因使用第一个版本(例如,投影具有线程关联性,或其他一些奇怪的情况),否则您应该使用第二个版本。
编辑:这是一些测试代码。虽然许多基准测试都存在缺陷,但结果相当具有结论性:
结果:
现在 PFX 中出现了很多启发式的东西,但很明显第一个结果根本没有被并行化,而第二个有。
Absolutely. In the first case, the projection and filtering will be done in series, and only then will anything be parallelized.
In the second case, both the projection and filtering will happen in parallel.
Unless you have a particular reason to use the first version (e.g. the projection has thread affinity, or some other oddness) you should use the second.
EDIT: Here's some test code. Flawed as many benchmarks are, but the results are reasonably conclusive:
Results:
Now there's a lot of heuristic stuff going on in PFX, but it's pretty obvious that the first result hasn't been parallelized at all, whereas the second has.
这确实很重要,而不仅仅是性能方面。
第一个和第二个查询的结果不相等。
有一种解决方案可以并行处理并保持原始顺序。
使用AsParallel().AsOrdered()。第三个查询显示了它。
结果:
我对此感到惊讶,但经过 10 次以上的测试运行后,结果是一致的。我调查了一下,结果发现这是 .Net 4.0 中的一个“bug”。在 4.5 中,AsParallel() 并不慢于 AsParallel().AsOrdered()
参考位于:
http://msdn.microsoft.com/en-us/library/dd460677(v=vs.110).aspx
It does matter and not just in performance.
The result of the first and the second queries are not equal.
There is solution to have parallel processing and keeping the original order.
Use
AsParallel().AsOrdered()
. Third query shows it.Result:
I was surprised about that, but the result was consistent after 10+ test run. I investigated a bit and it turned out to be a "bug" in .Net 4.0. In 4.5 AsParallel() is not slower than AsParallel().AsOrdered()
Reference is here:
http://msdn.microsoft.com/en-us/library/dd460677(v=vs.110).aspx