简体   繁体   中英

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 :

在此处输入图片说明

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 secondbut that's another unrelated topic )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM