gpt4 book ai didi

c# - AsParallel() 的最大并行度

转载 作者:IT王子 更新时间:2023-10-29 04:23:29 27 4
gpt4 key购买 nike

在使用 Parallel.ForEach 时,我们可以选择定义并行选项并设置最大并行度,例如:

Parallel.ForEach(values, new ParallelOptions {MaxDegreeOfParallelism = number}, value = > {
// Do Work
})

但是在执行 PLINQ 时:

Tabel.AsEnumberable()
.AsParallel()
.Where(//Logic)

我找不到设置 MaxDegreeOfParallelism 的方法。我也在网上查了一下,但没有找到任何东西。有人找到解决方法吗?任何帮助表示赞赏。

最佳答案

您可以使用 ParallelEnumerable.WithDegreeOfParallelism :

Sets the degree of parallelism to use in a query. Degree of parallelism is the maximum number of concurrently executing tasks that will be used to process the query.

var result = Tabel.AsEnumberable()
.AsParallel()
.WithDegreeOfParallelism(number)
.Where(/* predicate */);

编辑:

@svick 在 ParallelOptions.MaxDegreeOfParallelism vs PLINQ’s WithDegreeOfParallelism 上提供了出色的表现其中强调了两者之间的区别:

Parallel works using an under-the-covers concept we refer to as replicating tasks. The concept is that a loop will start with one task for processing the loop, but if more threads become available to assist in the processing, additional tasks will be created to run on those threads. This enables minimization of resource consumption. Given this, it would be inaccurate to state that ParallelOptions enables the specification of a DegreeOfParallelism, because it’s really a maximum degree: the loop starts with a degree of 1, and may work its way up to any maximum that’s specified as resources become available.

PLINQ is different. Some important Standard Query Operators in PLINQ require communication between the threads involved in the processing of the query, including some that rely on a Barrier to enable threads to operate in lock-step. The PLINQ design requires that a specific number of threads be actively involved for the query to make any progress. Thus when you specify a DegreeOfParallelism for PLINQ, you’re specifying the actual number of threads that will be involved, rather than just a maximum.

关于c# - AsParallel() 的最大并行度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25290389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com