Is there any way to limit the number of processors that the ThreadPool object will use? According to the docs, “You cannot set the number of worker threads or the number of I/O completion threads to a number smaller than the number of processors in the computer.”
So how can I limit my program to not consume all the processors?
After some experiments, I think I have just the thing. I’ve noticed that the
ThreadPoolconsiders the number of processors in the system as the number of processors available to the current process. This can work to your advantage.I have 4 cores in my CPU. Trying to call
SetMaxThreadswith 2:fails since I have 4 cores and so the numbers remain at their initial values (1023 and 1000 for my system).
However, like I said initially, the
ThreadPoolonly considers the number of processors available to the process, which I can manage usingProcess.ProcessorAffinity. Doing this:limits the available processors to the first two cores (since 3 = 11 in binary). Calling
SetMaxThreadsagain:should work like a charm (at least it did for me). Just make sure to use the affinity setting right at program start-up!
Of course, I would not encourage this hack, since anyway your process will be stuck with a limited number of cores for the entire duration of its execution.