Number of threads being used during Parallel.ForEach

耗尽温柔 提交于 2019-12-11 02:41:37

问题


I just did a simple experiment to show the total number of threads in a process using the code below.

Console.WriteLine("Total Number of Threads: {0}", Process.GetCurrentProcess().Threads.Count);

Parallel.ForEach(
            names,
            new ParallelOptions  {MaxDegreeOfParallelism = Environment.ProcessorCount },
            name =>
            {
                Console.WriteLine(name);
            });
Console.Read();
Console.WriteLine("Total Number of Threads: {0}", Process.GetCurrentProcess().Threads.Count);

I got 12 threads before the parallel.foreach and got 17 threads after the parallel.foreach.

Questions:

  1. Why is that the 5 threads used in Parallel.Foreach continue to run after the loop? Does it mean that if I have other Parallel.Foreach after this there will be more threads continuing to increase?
  2. Why is that the Parallel.Foreach don't use the 12 threads before? Is it because the 12 threads is currently being used by others?

回答1:


This behavior is non deterministic from the outsideview.

The Parallel class uses Threadpools. There are some decissions made on when to create new threads and when to use old ones. This also gives you performance and reduces the required amount of memorry.

There for after the parallel foreach some threads could (temporarly) still exist , which could be used for the threadpool activities. But as far as I know you cannot predict, if or how many threads will continue to exist.



来源:https://stackoverflow.com/questions/14869651/number-of-threads-being-used-during-parallel-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!