Parallel.For(Foreach) 将创建多少个线程?默认 MaxDegreeOfParallelism? [英] How many threads Parallel.For(Foreach) will create? Default MaxDegreeOfParallelism?

查看:23
本文介绍了Parallel.For(Foreach) 将创建多少个线程?默认 MaxDegreeOfParallelism?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,当我运行 Parallel.For/ForEach 循环时,会用到多少线程.

I want to know, how many threads will be used when I run Parallel.For/ForEach loop.

我发现,它可以通过 MaxDegreeOfParallelism 选项改变.

I found, that it can be changed by MaxDegreeOfParallelism option.

MSDN 上的 MaxDegreeOfParallelism 帮助说(链接):

MaxDegreeOfParallelism help on MSDN says (link):

默认情况下,For 和 ForEach 将使用任意多的线程底层调度程序提供,因此将 MaxDegreeOfParallelism 从默认仅限制将使用的并发任务数.

By default, For and ForEach will utilize however many threads the underlying scheduler provides, so changing MaxDegreeOfParallelism from the default only limits how many concurrent tasks will be used.

但我不知道调度程序底层提供了多少线程.

But I don't know how many threads underlying scheduler provides.

我怎样才能知道?

我可以用 9999999 次运行的循环来测试它,但是这个测试会显示数字,而不是确定该数字的规则.

I could test it with loop with 9999999 runs, however this test will show me number, but not the rule that determine that number.

稍后编辑/添加:

我在谷歌上搜索了sheduler max concurrency",我发现(在 MSDN - link),该 TashSheduler 类具有 MaximumConcurrencyLevel 属性,并且:

I googled for "sheduler max concurrency", and I found (at MSDN - link), that TashSheduler class has MaximumConcurrencyLevel property, and:

返回一个表示最大并发级别的整数.这默认调度程序返回 Int32.MaxValue.

Returns an integer that represents the maximum concurrency level. The default scheduler returns Int32.MaxValue.

那个 TaskSheduler 类被用作这些并行循环的底层调度程序"?

推荐答案

根据 MSDN:

任务并行库和 PLINQ 的默认调度程序使用 .NET Framework ThreadPool 来排队和执行工作.在 .NET Framework 4 中,ThreadPool 使用 System.Threading.Tasks.Task 类型提供的信息来有效地支持细粒度并行(短实时工作单元)通常代表并行任务和查询.

The default scheduler for Task Parallel Library and PLINQ uses the .NET Framework ThreadPool to queue and execute work. In the .NET Framework 4, the ThreadPool uses the information that is provided by the System.Threading.Tasks.Task type to efficiently support the fine-grained parallelism (short-lived units of work) that parallel tasks and queries often represent.

查看ThreadPool文档,它说:

每个进程有一个线程池.从 .NET Framework 4 开始,进程的线程池的默认大小取决于多个因素,例如虚拟地址空间的大小.进程可以调用GetMaxThreads 方法来确定线程数.可以使用SetMaxThreads 方法更改线程池中的线程数.

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method.

这篇关于Parallel.For(Foreach) 将创建多少个线程?默认 MaxDegreeOfParallelism?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆