When should I create threads and when should I use thread pool to run work items asynchronously?

 

        The ThreadPool generally results in better performance if your work items have a relatively short lifetime.  So if you typically create threads just to run small asynchronous tasks, you’ll get better performance by performing those tasks using the ThreadPool.  In these scenarios, the ThreadPool is more efficient primarily because it avoids the overhead of creating and destroying individual threads.  Also, because your work items are short in duration, you shouldn’t have to wait for a thread in the pool to become available.

On the other hand it’s advisable for developers to create dedicated Thread objects if their threads have a long lifetime, or if a thread might be blocked for a longer time ( to avoid prolonged occupation of one of the ThreadPool threads) or needs to run at a different priority.  Adjusting the priority of ThreadPool threads can be dangerous if the priority isn’t properly restored when you’re done.

Also, if you need to run a large number of work items and you don’t need concurrency, you may choose to create a dedicated Thread and re-use it to do the work.  The .NET Compact Framework will try to create a new worker thread in the ThreadPool  (up to a certain limit – 25 by default in version 2.0, 256 in version 1.0), if no worker thread is available to process your work immediately. By re-using your own thread you avoid a potential spike in a number of  ThreadPool threads.

你可能感兴趣的:(thread)