What is the difference between using the thread pool and a normal thread?

advertisements

I Was reading random questions and answers here on SO and came across this question:

C#, IAsyncResult and the thread pool

The question is asked is X method using the thread pool or using normal threads.

What's the difference between using the thread pool and a normal thread?


The threadpool is typically suitable for short running tasks. It has the limitation that it is a application-wide limited resource (25 per CPU), and there are a lot of internal classes that use the threadpoool, so if you perform a lot of long running tasks you will use up all the threads.

For long running tasks, it's better to use a manually created thread, with its background property set to true.

Note: In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

When Not to Use Thread Pool Threads

There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:

  • You require a foreground thread(!).

  • You require a thread to have a particular priority.

  • You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.

  • You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.

  • You need to have a stable identity associated with the thread, or to dedicate a thread to a task.

One big difference is that Unhandled exceptions on thread pool threads terminate the process; with these three exceptions:

  • A ThreadAbortException is thrown in a thread pool thread, because Abort was called.

  • An AppDomainUnloadedException is thrown in a thread pool thread, because the application domain is being unloaded.

  • The common language runtime or a host process terminates the thread.

Some good references are:

The Managed Thread Pool

Threading in C#

Programming the Thread Pool in the .NET Framework

Update: in response to comments. You can use the GetAvailableThreads method to determine the actual number of threads in the thread pool at any given time. ThreadPool.GetMaxThreads is a different quantity. Its the max allowed in the pool before requests are queued, not the actual number of threads currently in the pool.