The MaxDegreeOfParallelism
sets the maximum number of simultaneous threads that would be used for the Parallel.For()
. It does not mean this only threads would ever be used.
Different threads can allocated from the ThreadPool during execution Parallel.For()
of the, since ThreadPool threads is Specifi Cally designed to be reused.
The following program demonstrates. If you run it, you'll see that the total number of different threads being used can exceed 2, but the total number of thre Ads being used simultaneously never exceeds 2.
UsingSystem;UsingSystem.Collections.Concurrent;UsingSystem.Threading;UsingSystem.Threading.Tasks;NamespaceConsoleApp1{ Class Program { Static void Main() { ParallelOptionsPo= New ParallelOptions { Maxdegreeofparallelism = 2 }; VarActivethreads= New Concurrentdictionary<Int, bool> (); Parallel.For(0, 100,Po,X= {Activethreads[Thread.CurrentThread.Managedthreadid] = True; Console.WriteLine("Active Threads:" + String.Join(", ",Activethreads.Keys)); Threadsleep (200. Tryremove (thread. Currentthread. Managedthreadid, out Unused console. Readline} }} /span>
Limit number of processes in TPL