In this article, I give a sample console application with a task contained a Sleep of ten second ( like a process that take ten second 😉 to simulate an application with 200 task of ten second.
ThreadPool is a class that allows you to create task which are queuing and executing by the ThreadPool. It is better to use it than creating yourself all the plumbing of the management of thread ( I believe that Microsoft engineer work well ;-).
the rule is to take one thread by CPU to make real multithread but in many cases you can use as in my sample an example that demonstrate that it is not true every time
I use a 8 cpu computer so in my ThreadPool when I call GetMinThreads it return 8 thread (one by CPU). The application launch 200 task that wait 10 second.
when running the application, you see that it took only 11 seconds instead of 200×11 second :
launch task manager to see the number of thread: first select view->Select Columns
and select Thread column:
there are 203 thread with 3 thread for console and main application:
if I set the minimum thread at 8, ThreadPool will use it so it execute the 200 task 8 by 8 . To do it modify the code by using SetMinThread :
Now the application spend more time although we respect the rule : 1 thread by CPU, we have 8 CPU so we use 8 threads 😉 Now it take 67 seconds (67011ms)!
you can observe that the ThreadPool has created new thread (more than 8) step by step which explains that application run on 67seconds and not on 200/8 x 10 seconds that is 250seconds. Don’t forget that you can set min and max thread so the ThreadPool can add or remove thread to execute all tasks.
If you want to fix the number of thread you can set the same number in SetMinThread method and SetMaxThread method
So if you have to make a lot of task try different number of threads using the SetMinThreads