简体   繁体   English

PLINQ和AsParallel()

[英]PLINQ and AsParallel()

What is the difference between this code: 这段代码有什么区别:

int[] tab = new int[] { 1, 2, 3, 4, 5 };

List<int> result1 = (from t in tab
                     where t > 2
                     select t).AsParallel().ToList();

and this: 和这个:

List<int> result2  = (from t in tab.AsParallel()
                      where t > 2
                      select t).ToList();

?

Everything after a call to AsParallel will be parallelized. 调用AsParallel 的所有内容都将被并行化。

So in your first listing only the ToList operation will be parallelized as where in the second code sample, the entire query will be parallelized. 因此,在您的第一个列表中,只有ToList操作将被并行化为第二个代码示例中的位置,整个查询将被并行化。

Let's go back ..... 我们回去吧 .....

在此输入图像描述

There are two strategies for partitioning work among threads: data parallelism and task parallelism. 在线程之间划分工作有两种策略:数据并行和任务并行。

Your are in : structured data parallelism zone. 您的位置: structured data parallelism区域。 ( in plinq) (在plinq)

So the DATA which we deal with should be divided to threads. 所以我们处理的DATA应该分成线程。

Your first code is pointless. 你的第一个代码毫无意义。

Look at the syntax of AsParallel : 看看AsParallel的语法:

public static ParallelQuery AsParallel(
    this IEnumerable source
)

AsParallel should be applied on IEnumerable . AsParallel应该应用于IEnumerable ( like in both of your examples...but - ) (就像在你的两个例子中......但是 - )

The whole point here is to divide work to threads . 这里的重点是将工作划分为线程。

This divides DATA to threads which perform the SAME operation. 这将DATA分配给执行SAME操作的线程。

In the second code you DO divide DATA to threads which will perform same operation. 在第二个代码中,您将DATA分配给将执行相同操作的线程。 ( hence you get better performance) (因此你会获得更好的表现)

But in the first code , the whole "making cores hot operation" is done in single thread. 但是在第一个代码中,整个“make core hot operation”是在单线程中完成的。 ( where clause... ) - so you're missing the whole point where clause... ) - 所以你错过了重点

Notice - it would be worth something if : 注意 - 如果有以下情况,那将是值得的:

...(from t in tab
    where t > 2
    select t).AsParallel().where(....)....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM