Number of threads being used during Parallel.ForEa

2019-07-14 19:07发布

问题:

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.