hisoka21
hisoka21

Reputation: 923

Number of threads being used during Parallel.ForEach

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?

Upvotes: 2

Views: 5736

Answers (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.

Upvotes: -2

Boas Enkler
Boas Enkler

Reputation: 12557

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.

Upvotes: 7

Related Questions