There are a lot of dis­cus­sions on the pros and cons of using the Thread­Pool and cre­at­ing your own threads. Hav­ing spent a bit of time read­ing what oth­ers have to say, here’s a sum­mary of the things I’ve picked up on.

The prob­lem with cre­at­ing your own threads

Cre­at­ing and destroy­ing threads has a high CPU usage, so when you need to per­form lots of small, sim­ple tasks con­cur­rently the over­head of cre­at­ing your own threads can take up a sig­nif­i­cant por­tion of the CPU cycles and severely affect the final response time. This is espe­cially true in stress con­di­tions where exe­cut­ing mul­ti­ple threads can push CPU to 100% and most of the time would be wasted in con­text switch­ing (swap­ping threads in and out of the proces­sor along with their memory).

Using the Thread Pool

This is where the .Net Thread Pool comes in, where a num­ber of threads are cre­ated ahead of time and kept around to pick up any work items you give them to do, with­out the over­head asso­ci­ated with cre­at­ing your own threads.

When not to use the Thread Pool

In an ideal world you would always want to use the Thread Pool, but there are some real-world lim­i­ta­tions. Most impor­tantly, and the rea­son why most experts would tell you not to use the Thread Pool except for brief jobs is that: there is a lim­ited num­ber of threads in the .Net Thread Pool (250 per CPU by default), and they are being used by many of the .Net frame­work classes (e.g. timer events are fired on thread pool threads) so you wouldn’t want your appli­ca­tion to hog the thread pool.

There are also a num­ber of sit­u­a­tions where you shouldn’t use the thread pool:

  • You require a fore­ground thread, all the thread pool threads are back­ground threads
  • You require a thread to have a par­tic­u­lar priority.
  • You have tasks that cause the thread to block for long peri­ods of time. The thread pool has a max­i­mum num­ber of threads, so a large num­ber of blocked thread pool threads might pre­vent tasks from starting.
  • You need to place threads into a single-threaded apart­ment. All Thread­Pool threads are in the mul­ti­threaded apartment.
  • You need to have a sta­ble iden­tity asso­ci­ated with the thread, or to ded­i­cate a thread to a task.

Excep­tions in Thread Pool threads

Unhan­dled excep­tions on thread pool threads ter­mi­nate the process with 3 exceptions:

When to cre­ate your own threads

As I’ve men­tioned already, cre­at­ing your own threads is bad when lots of sim­ple tasks require a rel­a­tive large over­head in con­text switch­ing, and the Thread Pool is bad for long run­ning, or block­ing tasks. Which leads to the nat­ural con­clu­sion :-P – cre­ate your own threads for long run­ning, or block­ing tasks!

Part­ing thoughts…

When work­ing with the Thread Pool there are some use­ful meth­ods at your dis­pos­able, including:

  • GetAvail­ableThreads method which returns the num­ber of threads avail­able to you
  • Get­MinThreads method returns the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Get­Max­Threads method returns the max num­ber of thread pool threads that can be active concurrently
  • Set­MinThreads method sets the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Set­Max­Threads method sets the num­ber of thread pool threads that can be active concurrently

If you’re inter­ested in how the Thread­Pool class dynam­i­cally man­ages the size of the thread pool under the hood (despite giv­ing you the option to set min and max threads) you should have a read of Pedram Razai’s blog post in the ref­er­ence section.

And before you go, I men­tioned ear­lier that all Thread Pool threads are back­ground threads, so how do they dif­fer from fore­ground threads? Well, fore­ground and Back­ground threads are iden­ti­cal with one excep­tion: a back­ground thread does not keep the man­aged exe­cu­tion envi­ron­ment run­ning. Once all fore­ground threads have been stopped in a man­aged process (where the .exe file is a man­aged assem­bly), the sys­tem stops all back­ground threads and shuts down.

Ref­er­ences:

Stack­Over­flow ques­tion on Thread Pool vs Thread Spawning

Another Stack­Over­flow ques­tion on Thread Pool vs Thread Spawning

Stack­Over­flow ques­tion on when to use the Thread Pool in C#

Stack­Over­flow ques­tion on man­ag­ing the size of the Thread Pool in C#

Stack­Over­flow ques­tion with detail on the throt­tling behav­iour of the ThreadPool

MSDN arti­cle on The Man­aged Thread Pool

MSDN C# Pro­gram­ming Guide : how to use a ThreadPool

MSDN arti­cle on why we need a thread pool

Jon Skeet’s intro­duc­tory arti­cle on Multi-threading in C#

Pedram Rezaei’s blog post on ded­i­cated threads vs thread­pool threads

Smart Thread Pool project on CodePlex

Share

7 Responses to “Threading — using the ThreadPool vs. creating your own threads”

  1. […] I’ve men­tioned in my pre­vi­ous post, the biggest prob­lem with using the .Net Thread­Pool is that there’s a lim­ited num­ber of […]

  2. […] uses the frame­work Thread­Pool (which also has fur­ther per­for­mance impli­ca­tions, see here), there is a bal­ance between the num­ber of con­cur­rent threads and how much time the CPU […]

  3. Hey guys,

    My name is Daniel and I am from Stir­ling in the United King­dom. I have not long ago dis­cov­ered this forum and I like it alot.
    I am a bit shy so I wont write much about myself but maybe when I will get more con­fort­able, you guys will get to know me bet­ter!
    My main hob­bies are play­ing piano and watch­ing movies. I also like out­door activites but the tem­per­a­ture has been ter­ri­ble for the last days or so here in Stir­ling in the city|.

    I was won­der­ing if any­one else here is from the united King­dom too?

    I am glad to have joined this forum!
    Cheers!
    :)

    Daniel

    PS: I apol­o­gize if this was posted in the wrong topic. I could not find the right one!

  4. […] a new thread or use a Smart­Thread­Pool instance. I’ve dis­cussed these aspect in more detail here and here if you’re […]

  5. […] Auf­gaben hinge­gen ist der Pool nicht geeignet, da es lediglich (als stan­dard) zwis­chen 25 und 250 Threads (pro CPU) (je nach .net Frame­work Ver­sion) in diesem Pool […]

  6. […] cov­ered the topic of using Smart­Thread­Pool and the frame­work thread pool in more details here and here, this post will instead focus on a more spe­cific sce­nario where the rate of new work […]

  7. JohnRob says:

    Very nice and infor­ma­tive arti­cle that beau­ti­fully elab­o­rate the basics idea of C# Thread­Pool. Check this link too its also hav­ing nice post with won­der­ful expla­na­tion on C# Thread­Pool.
    http://www.mindstick.com/Articles/8a6ce546-6516-46c7-9398-edc0d28a38f1/?ThreadPool%20in%20C#%20Programming

    Thanks Every­one!!

Leave a Reply