Expand
ThreadPool Class

Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Syntax

'Declaration

<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
	ExternalThreading := True)> _
Public NotInheritable Class ThreadPool
Remarks

Many applications create threads that spend a great deal of time in the sleeping state, waiting for an event to occur. Other threads might enter a sleeping state only to be awakened periodically to poll for a change or update status information. Thread pooling enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. One thread monitors the status of several wait operations queued to the thread pool. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function.

NoteNote

The threads in the managed thread pool are background threads. That is, their IsBackground properties are true. This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.

You can also queue work items that are not related to a wait operation to the thread pool. To request that a work item be handled by a thread in the thread pool, call the QueueUserWorkItem method. This method takes as a parameter a reference to the method or delegate that will be called by the thread selected from the thread pool. There is no way to cancel a work item after it has been queued.

Timer-queue timers and registered wait operations also use the thread pool. Their callback functions are queued to the thread pool.

There is one thread pool per process. The thread pool has a default size of 250 worker threads per available processor, and 1000 I/O completion threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

NoteNote

Unmanaged code that hosts the .NET Framework can change the size of the thread pool by using the CorSetMaxThreads function, defined in the mscoree.h file.

The thread pool maintains a minimum number of idle threads. For worker threads, the default value of this minimum is the number of processors. The GetMinThreads method obtains the minimum numbers of idle worker and I/O completion threads.

When all thread pool threads have been assigned to tasks, the thread pool does not immediately begin creating new idle threads. To avoid unnecessarily allocating stack space for threads, it creates new idle threads at intervals. The interval is currently half a second, although it could change in future versions of the .NET Framework.

If an application is subject to bursts of activity in which large numbers of thread pool tasks are queued, use the SetMinThreads method to increase the minimum number of idle threads. Otherwise, the built-in delay in creating new idle threads could cause a bottleneck.

NoteNote

Unnecessarily increasing the number of idle threads can also cause performance problems. Stack space must be allocated for each thread. If too many tasks start at the same time, all of them might appear to be slow. Finding the right balance is a performance-tuning issue.

When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, data that is placed in thread local storage by one method can be exposed to any other method that is executed by the same thread pool thread. A method that accesses a field that is marked with the ThreadStaticAttribute attribute could encounter different data depending on which thread pool thread executes it.

Starting with the .NET Framework version 2.0 Service Pack 1, the throughput of the thread pool is significantly improved for applications that make heavy use of small thread pool tasks. These applications will see improvements in three areas: queuing tasks, dispatching thread pool threads, and dispatching I/O completion threads.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

TopicLocation
How to: Create an Asynchronous HTTP HandlerBuilding ASP .NET Web Applications
How to: Create an Asynchronous HTTP HandlerBuilding ASP .NET Web Applications
Walkthrough: Creating an Asynchronous HTTP HandlerBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Creating an Asynchronous HTTP HandlerBuilding ASP .NET Web Applications in Visual Studio
Examples


Imports System
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Queue the task.
        ThreadPool.QueueUserWorkItem( _
            New WaitCallback(AddressOf ThreadProc) _
            )
        ' Note that you do not have to create the WaitCallback delegate
        ' explicitly in Visual Basic.  The following line also queues 
        ' the task:
        'ThreadPool.QueueUserWorkItem(AddressOf ThreadProc)

        Console.WriteLine("Main thread does some work, then sleeps.")
        ' If you comment out the Sleep, the main thread exits before
        ' the thread pool task runs.  The thread pool uses background
        ' threads, which do not keep the application running.  (This
        ' is a simple example of a race condition.)
        Thread.Sleep(1000)

        Console.WriteLine("Main thread exits.")
    End Sub

    ' This thread procedure performs the task.
    Shared Sub ThreadProc(stateInfo As Object)
        ' No state object was passed to QueueUserWorkItem, so 
        ' stateInfo is null.
        Console.WriteLine("Hello from the thread pool.")
    End Sub
End Class


Inheritance Hierarchy

System.Object
  System.Threading.ThreadPool
Thread Safety

This type is thread safe.

Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Community ContentAdd
ThreadPool.GetMaxThreads() shows only 100 per CPU
Edit: I give up trying to make this work. This feature is awful and keeps mangling my text and it adds in weird stuff. Oh well.

This article says that the max thread count should be 250 per CPU, but my tests as well as the tests by Steve Sanderson (Author of Pro ASP.NET MVC Framework 2) show that the max thread count is 100 per CPU.

The following code is what was used to get these numbers:
int wt;
int cpt;
ThreadPool.GetMaxThreads(out wt, out cpt);

Inspect the value of wt and you'll see that it is (100*CPUs). Are we missing something or is the documentation incorrect? If it is incorrect, this is a very large difference.
Page view tracker