2

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?
hisoka21
  • 855
  • 1
  • 12
  • 21

2 Answers2

7

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.

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
-2

My understanding is also that you can't predict how many threads will run. I have run into issues where the number of threads was higher than what I desired, which I handled by using AutoResetEvent.

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/29794029) – m4n0 Sep 11 '21 at 06:05