11

Where and how to check through code number of threads available in threadpool.

What i want is: For example if no of threads in threadpool are 10 then at any given time I should not be using say more than 3 threads. Once an existing thread gets free, I should start a new task, keeping max count 3.

dotnetavalanche
  • 804
  • 2
  • 12
  • 25
  • 6
    That management is already done by the thread pool. It starts and stops new threads as needed, using a feedback loop. Just start tasks whenever needed, and let the thread pool take care of the scheduling, that's its job. – Kevin Gosse Jun 13 '16 at 11:01
  • Why do you want to *"keeping max count 3"*? Is it a [requirement](http://stackoverflow.com/a/10343983/1997232) or [premature optimization](http://stackoverflow.com/a/385529/1997232)? – Sinatr Jun 13 '16 at 11:14
  • I am not sure of CPU count on production server. So its kind of premature optimization from my side. 3 is not the exact count. Based on more details I may change it to 4 or 6 or 2. – dotnetavalanche Jun 13 '16 at 11:21
  • 1
    Don't re-invent ThreadPool.SetMaxThreads(). Tinkering like this is a mistake, the thread pool manager really doesn't need help like this. It will start extra threads beyond the optimum number because it should, important to deal with tp threads that block too much and to avoid deadlock. – Hans Passant Jun 13 '16 at 12:38
  • ThreadPool exposes methods to provide that info. However, the ThreadPool will automatically spawn and destroy threads as it sees fit, usually aiming to have one available thread per core. You should probably not mess with it, unless you know exactly what you're doing and you have a very good reason for doing it. – Falanwe Jun 13 '16 at 13:18
  • This question should be marked as answered – TheGeneral Oct 16 '18 at 06:27

1 Answers1

16

ThreadPool.GetAvailableThreads will give you number of available threads. ThreadPool.GetMaxThreads will give you max number of threads. The difference will give you the number of active threads.

kiran
  • 396
  • 3
  • 11