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:
- 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?
- 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?