ThreadPool Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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.

Inheritance Hierarchy

System.Object
  System.Threading.ThreadPool

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

Syntax

'Declaration
Public NotInheritable Class ThreadPool
public static class ThreadPool

The ThreadPool type exposes the following members.

Methods

  Name Description
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetMaxThreads Retrieves the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetMinThreads Retrieves the number of idle threads the thread pool maintains in anticipation of new requests.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 QueueUserWorkItem(WaitCallback) Queues a method for execution. The method executes when a thread pool thread becomes available.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean) Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean) Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) Registers a delegate to wait for a WaitHandle, specifying a TimeSpan value for the time-out.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean) Registers a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 SetMaxThreads Security Critical. Sets the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 SetMinThreads Security Critical. Sets the number of idle threads the thread pool maintains in anticipation of new requests.

Top

Remarks

The thread pool 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:

If you need to access user interface elements from code that is executed by a thread from the thread pool, use the System.Windows.Threading.Dispatcher class to run your code on the user interface thread.

The threads in the managed thread pool are background threads. That is, their IsBackground properties are true.

You can also queue work items that are not related to a wait operation. 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 processor, and 1000 I/O completion threads.

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.

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.

Topic Location
How to: Create an Asynchronous HTTP Handler Building ASP .NET Web Applications
How to: Create an Asynchronous HTTP Handler Building ASP .NET Web Applications

Examples

The following example uses the QueueUserWorkItem(WaitCallback) method overload to queue a task, which is represented by the ThreadProc method, to execute when a thread becomes available. No task information is supplied with this overload. Therefore, the information that is available to the ThreadProc method is limited to the object the method belongs to.

The example displays its output in a TextBlock on the UI thread. To access the TextBlock from the callback thread, the example uses the Dispatcher property to obtain a Dispatcher object for the TextBlock, and then uses the Dispatcher.BeginInvoke method to make the cross-thread call.

Imports System.Threading

Class Example

    ' This is the UI element that receives the output from the example.
    Private Shared outputBlock As System.Windows.Controls.TextBlock

    ' The Demo method runs the example. It saves the TextBlock that is 
    ' used for output, and sets up an event handler to start tasks.
    Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

        Example.outputBlock = outputBlock
        outputBlock.Text = "Click here to start a background task." & vbCrLf

        ' Set up an event handler to start a task when the TextBlock 
        ' is clicked.
        AddHandler outputBlock.MouseLeftButtonUp, AddressOf HandleMouseUp

    End Sub

    ' Clicking the TextBlock queues a delegate to perform a task on a 
    ' thread pool thread.
    Private Shared Sub HandleMouseUp(ByVal sender As Object, _
                          ByVal e As System.Windows.Input.MouseButtonEventArgs) 

        ThreadPool.QueueUserWorkItem(AddressOf AppendTextTask)

        ' Note: The stateInfo object for the task in this example is
        ' Nothing, because this overload of QueueUserWorkItem does not
        ' take a stateInfo parameter. 
    End Sub 

    ' This method performs the task, which is to append text to the
    ' TextBlock. To communicate with objects on the UI thread, get the 
    ' Dispatcher for one of the UI objects. Use the Dispatcher object's 
    ' BeginInvoke method to queue a delegate that will run on the UI thread,
    ' and therefore can safely access UI elements like the TextBlock. In 
    ' this example, the delegate is stored in the field named 'append'.
    Private Shared Sub AppendTextTask(ByVal stateInfo As Object)

        outputBlock.Dispatcher.BeginInvoke(append, "Hello from the thread pool." & vbCrLf)

    End Sub

    ' Invoking this delegate runs the AppendText method.
    Private Shared append As New Action(Of String)(AddressOf AppendText) 

    ' The AppendText method can safely access UI elements because it is run
    ' on the UI thread, by using the Dispatcher.BeginInvoke method.
    Private Shared Sub AppendText(ByVal text As String) 

        outputBlock.Text &= text

    End Sub
End Class 

' This code produces output similar to the following:
'
'Click here to start a background task.
'Hello from the thread pool.
'Hello from the thread pool.
'Hello from the thread pool.
using System;
using System.Threading;

class Example
{
    // This is the UI element that receives the output from the example.
    private static System.Windows.Controls.TextBlock outputBlock;

    // The Demo method runs the example. It saves the TextBlock that is 
    // used for output, and sets up an event handler to start tasks.
    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
    {
        Example.outputBlock = outputBlock;
        outputBlock.Text = "Click here to start a background task.\r\n";

        // Set up an event handler to start a task when the TextBlock 
        // is clicked.
        outputBlock.MouseLeftButtonUp += HandleMouseUp;
    }

    // Clicking the TextBlock queues a delegate to perform a task on a 
    // thread pool thread.
    private static void HandleMouseUp(object sender, 
                                      System.Windows.Input.MouseButtonEventArgs e)
    {
        ThreadPool.QueueUserWorkItem(AppendTextTask);

        // Note: The stateInfo object for the task in this example is
        // Nothing, because this overload of QueueUserWorkItem does not
        // take a stateInfo parameter. 
    }

    // This method performs the task, which is to append text to the
    // TextBlock. To communicate with objects on the UI thread, get the 
    // Dispatcher for one of the UI objects. Use the Dispatcher object's 
    // BeginInvoke method to queue a delegate that will run on the UI thread,
    // and therefore can safely access UI elements like the TextBlock.
    private static void AppendTextTask(object stateInfo)
    {
        outputBlock.Dispatcher.BeginInvoke(delegate () {
            outputBlock.Text += "Hello from the thread pool.\r\n";
        });
    }
}

/* This code produces output similar to the following:

Click here to start a background task.
Hello from the thread pool.
Hello from the thread pool.
Hello from the thread pool.
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

This type is thread safe.