Reputation: 923
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:
Upvotes: 2
Views: 5736
Reputation: 135
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
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