简体   繁体   中英

ThreadPool.QueueUserWorkItem Vs new Thread

I have the following code:

static void Main(string[] args)
{
    Console.Write("Press ENTER to start...");
    Console.ReadLine();

    Console.WriteLine("Scheduling work...");
    for (int i = 0; i < 1000; i++)
    {
        //ThreadPool.QueueUserWorkItem(_ =>
        new Thread(_ =>
            {
                Thread.Sleep(1000);
            }).Start();
    }
    Console.ReadLine();
}

According to the textbook C# 4.0 Unleashed by Bart De Smet (page 1466), using new Thread should mean using many more threads than if you use ThreadPool.QueueUserWorkItem which is commented out in my code. However I've tried both, and seen in Resource Monitor that with "new Thread", there are about 11 threads allocated, however when I use ThreadPool.QueueUserWorkItem, there are about 50. Why am I getting the opposite outcome of what is mentioned in this book?

Also why if you increase the sleep time, do you get many more threads allocated when using ThreadPool.QueueUserWorkItem?

new Thread() just creates a Thread object; you forgot to call Start() (which creates the actual thread that you see in resource monitor).

Also, if you are looking at the number of threads after the sleep has completed, you won't see any of the new Thread s as they have already exited. On the other hand, the ThreadPool keeps threads around for some time so it can reuse them, so in that case you can still see the threads even after the sleep has completed.

With new Thread() , you might be seeing the number staying around 160 because it took one second to start that many threads, so by the time the 161st thread is started, the first thread is already finished. You should see a higher number of threads if you increase the sleep time.

As for the ThreadPool , it is designed to use as few threads as possible while also keeping the CPU busy. Ideally, the number of busy threads is equal to the number of CPU cores. However, if the pool detects that its threads are currently not using the CPU (sleeping, or waiting for another thread), it starts up more threads (at a rate of 1/second, up to some maximum) to keep the CPU busy.

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