Royi Namir
Royi Namir

Reputation: 148524

Thread-pool don't use threads as expected?

I'm trying to see what happens to the thread-pool when I extremely use it's threads :

So I run this test :

void Main()
{ 
  int AvaliableWorker,AvaliableioCompletion,MaxWorker,MaxioCompletion;

  for (int i=0;i<1028;i++) Task.Factory.StartNew(()=>{Thread.Sleep(5000);});

  Thread.Sleep(2000); // give the loop some time to run threads....

  ThreadPool.GetAvailableThreads(out AvaliableWorker, out AvaliableioCompletion);
  Console.WriteLine("{0} / {1}", AvaliableWorker, AvaliableioCompletion);

  ThreadPool.GetMaxThreads(out MaxWorker, out MaxioCompletion); 
  Console.WriteLine("{0} / {1}", MaxWorker, MaxioCompletion); 

}

However , When I run it on my .net4/32bit environment (console) , I get these results :

**1015** / 1000
1023 / 1000

Running again :

**1009** / 1000
1023 / 1000

The question is about the bold numbers :

Question

Fw.4 sets a default max thread-pool worker threads creation up to 1023 (as you can see).

But looking at GetAvailableThreads :

enter image description here

If so , how come I still get big values like 1015 , 1009 right as I make 1028 threads sleep ?

I mean , 1023-1028 = negative number : ( in other words : "no more threads my friend , I will create them now on demand via 2 threads per second but that's another unrelated topic)

Upvotes: 1

Views: 105

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273244

right as I make 1028 threads sleep ?

You didn't. You queued about a 1000 Tasks, not (yet) Threads. Still waiting to run when you WriteLine() the results.

The actual number of pool threads at that moment: 1023 - 1015 = 8.

Make the Sleep() after the for loop a little longer (seconds) and you will see a lower number of available threads, ie a higher number of pool threads.

Upvotes: 2

Related Questions