.NET中的多个Parallel.ForEach循环 [英] Multiple Parallel.ForEach loops in .Net
问题描述
在.Net进程中,只有一个托管线程池.我们可以通过公共属性根据需要设置最小和最大线程数.
In a .Net process, there is only one managed thread pool. We can set the minimum and maximum thread count as needed via public properties.
在.Net中,我们还有 Parallel.ForEach
,它可以从后台的托管线程池中获取线程.
In .Net, we also have Parallel.ForEach
that gets its threads from this managed thread pool under the hood.
在 Parallel.ForEach
中,我们还可以设置 MaxDegreeOfParallelism
来限制最大线程数.
In Parallel.ForEach
we can also set the MaxDegreeOfParallelism
to limit the maximum number of threads.
我有两个在parrallel中运行的 Parallel.ForEach
.一个将 MaxDegreeOfParallelism
设置为3,另一个将其设置为7.
I have two Parallel.ForEach
running in parrallel. One has MaxDegreeOfParallelism
set to 3 and the other has set to 7.
我的问题是:我的两个 Parallel.ForEach
循环是否在后台使用相同的线程池.如果是,则 Parallel.ForEach
如何使用 MaxDegreeOfParallelism
限制线程.多少倍 Parallel.ForEach
循环和一个托管线程池可以一起工作吗?如果您可以在深入了解.net核心源代码之前提供高级说明或一些指针,那将真正有帮助.
My question is: Does both my Parallel.ForEach
loops use the same thread pool under the hood. If yes, how does Parallel.ForEach
limits the threads with MaxDegreeOfParallelism
. How multiple
Parallel.ForEach
loops and one managed thread pool work together?
It'll really help if you can provide a high level explanation or some pointers before I peak into the .net core source code.
推荐答案
-
我的两个
Parallel.ForEach
循环都使用相同的线程池吗?Does both my
Parallel.ForEach
loops use the same thread pool under the hood.是
Parallel.ForEach
如何通过MaxDegreeOfParallelism限制线程.How does
Parallel.ForEach
limits the threads with MaxDegreeOfParallelism.ParallelOptions.MaxDegreeOfParallelism 获取或设置由
ParallelOptions.MaxDegreeOfParallelism Gets or sets the maximum number of concurrent tasks enabled by this ParallelOptions instance.
默认情况下,Parallel类上的方法尝试使用所有可用的处理器,这些方法是不可取消的,并且以默认TaskScheduler(TaskScheduler.Default)为目标.使用ParallelOptions可以覆盖这些默认设置.
By default, methods on the Parallel class attempt to use all available processors, are non-cancelable, and target the default TaskScheduler (TaskScheduler.Default). ParallelOptions enables overriding these defaults.
多个
Parallel.ForEach
循环和一个托管线程池如何一起工作?How multiple
Parallel.ForEach
loops and one managed thread pool work together?它们共享相同的线程池.如所述此处:
They share the same thread pool. As it is described here:
通常,您不需要修改此设置.但是,您可以选择在诸如以下的高级使用场景中显式设置它:
Generally, you do not need to modify this setting. However, you may choose to set it explicitly in advanced usage scenarios such as these:
同时运行多个算法并想要手动定义每个算法可以使用多少系统时.您可以为每个设置MaxDegreeOfParallelism值.
这篇关于.NET中的多个Parallel.ForEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!