ThreadPool 类

定义

提供一个线程池,该线程池可用于执行任务、发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

public ref class ThreadPool abstract sealed
public static class ThreadPool
type ThreadPool = class
Public Class ThreadPool
继承
ThreadPool

示例

在下面的示例中,主应用程序线程会将名为 ThreadProc 的方法排队,以便在线程池线程上执行,休眠一秒钟,然后退出。In the following example, the main application thread queues a method named ThreadProc to execute on a thread pool thread, sleeps for one second, and then exits. @No__t-0 方法只显示一条消息。The ThreadProc method simply displays a message.

using namespace System;
using namespace System::Threading;

ref class Example
{
public:

   // This thread procedure performs the task.
   static void ThreadProc(Object^ stateInfo)
   {
      
      // No state object was passed to QueueUserWorkItem, so stateInfo is 0.
      Console::WriteLine( "Hello from the thread pool." );
   }
};

int main()
{
   // Queue the task.
   ThreadPool::QueueUserWorkItem(gcnew WaitCallback(Example::ThreadProc));

   Console::WriteLine("Main thread does some work, then sleeps.");
   
   Thread::Sleep(1000);
   Console::WriteLine("Main thread exits.");
   return 0;
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.
using System;
using System.Threading;

public class Example 
{
    public static void Main() 
    {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(ThreadProc);
        Console.WriteLine("Main thread does some work, then sleeps.");
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) 
    {
        // No state object was passed to QueueUserWorkItem, so stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Queue the work for execution.
        ThreadPool.QueueUserWorkItem(AddressOf ThreadProc)
        
        Console.WriteLine("Main thread does some work, then sleeps.")

        Thread.Sleep(1000)

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

    ' This thread procedure performs the task.
    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 Module
' The example displays output like the following:
'       Main thread does some work, then sleeps.
'       Hello from the thread pool.
'       Main thread exits.

如果注释掉对 Thread.Sleep 方法的调用,则在线程池线程上运行方法之前,主线程将退出。If you comment out the call to the Thread.Sleep method, the main thread exits before method runs on the thread pool thread. 线程池使用后台线程,如果所有前台线程均已终止,则不会使应用程序保持运行。The thread pool uses background threads, which do not keep the application running if all foreground threads have terminated. (这是争用条件的一个简单示例。)(This is a simple example of a race condition.)

注解

许多应用程序创建线程,在休眠状态中花费大量时间等待事件发生。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. 使用线程池,可以通过向应用程序提供由系统管理的工作线程池,来更有效地使用线程。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. 使用线程池线程的操作示例包括:Examples of operations that use thread pool threads include the following:

  • 创建 @no__t 0 或 Task<TResult> 对象以异步执行某些任务时,默认情况下,任务计划在线程池线程上运行。When you create a Task or Task<TResult> object to perform some task asynchronously, by default the task is scheduled to run on a thread pool thread.

  • 异步计时器使用线程池。Asynchronous timers use the thread pool. 线程池线程执行来自 @no__t 0 类的回调,并引发来自 @no__t 类的事件。Thread pool threads execute callbacks from the System.Threading.Timer class and raise events from the System.Timers.Timer class.

  • 使用已注册的等待句柄时,系统线程会监视等待句柄的状态。When you use registered wait handles, a system thread monitors the status of the wait handles. 等待操作完成后,线程池中的工作线程会执行相应的回调函数。When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function.

  • 调用 QueueUserWorkItem 方法将方法排队,以便在线程池线程上执行。When you call the QueueUserWorkItem method to queue a method for execution on a thread pool thread. 为此,可将方法传递给 @no__t 0 的委托。You do this by passing the method a WaitCallback delegate. 委托具有签名The delegate has the signature

    void WaitCallback(Object state)  
    
    Sub WaitCallback(state As Object)  
    

    其中 state 是包含要由委托使用的数据的对象。where state is an object that contains data to be used by the delegate. 可以通过调用 @no__t 0 方法将实际数据传递到委托。The actual data can be passed to the delegate by calling the QueueUserWorkItem(WaitCallback, Object) method.

备注

托管线程池中的线程是后台线程。The threads in the managed thread pool are background threads. 也就是说,其 IsBackground 属性 @no__t 为-1。That is, their IsBackground properties are true. 这意味着,在所有前台线程退出后,@no__t 0 线程不会使应用程序保持运行。This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.

重要

当线程池重用某个线程时,它不会清除线程本地存储区中的数据或用 ThreadStaticAttribute 特性标记的字段中的数据。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. 因此,当某个方法检查线程本地存储区或标记有 ThreadStaticAttribute 属性的字段时,它所找到的值可能会从先前使用线程池线程的过程中遗留。Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.

你还可以将与等待操作无关的工作项排队到线程池。You can also queue work items that are not related to a wait operation to the thread pool. 若要请求由线程池中的线程处理工作项,请调用 QueueUserWorkItem 方法。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. .NET Framework 4.NET Framework 4 开始,进程的线程池的默认大小取决于若干因素,例如虚拟地址空间的大小。Beginning with the .NET Framework 4.NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. 进程可以调用 GetMaxThreads 方法,以确定线程数。A process can call the GetMaxThreads method to determine the number of threads. 可以使用 @no__t 0 方法更改线程池中的线程数。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.

备注

承载 .NET Framework 的非托管代码可以使用 mscoree.dll 文件中定义的 CorSetMaxThreads 函数更改线程池的大小。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.

线程池按需提供新的工作线程或 i/o 完成线程,直到达到每个类别的最小值。The thread pool provides new worker threads or I/O completion threads on demand until it reaches the minimum for each category. 达到最小值时,线程池可以在该类别中创建更多的线程,或等待某些任务完成。When a minimum is reached, the thread pool can create additional threads in that category or wait until some tasks complete. .NET Framework 4.NET Framework 4 开始,线程池创建和销毁工作线程以优化吞吐量,吞吐量被定义为每个单位时间完成的任务数。Beginning with the .NET Framework 4.NET Framework 4, the thread pool creates and destroys worker threads in order to optimize throughput, which is defined as the number of tasks that complete per unit of time. 线程过少可能无法实现可用资源的最优利用,而线程过多则可能增加资源争用。Too few threads might not make optimal use of available resources, whereas too many threads could increase resource contention.

备注

需求较低时,线程池线程的实际数量可以低于最小值。When demand is low, the actual number of thread pool threads can fall below the minimum values.

可以使用 GetMinThreads 方法来获取这些最小值。You can use the GetMinThreads method to obtain these minimum values.

注意

可以使用 @no__t 0 方法增加最小线程数。You can use the SetMinThreads method to increase the minimum number of threads. 但是,不必要地增加这些值可能导致性能问题。However, unnecessarily increasing these values can cause performance problems. 如果在同一时间开始太多的任务,则所有任务均可能会很慢。If too many tasks start at the same time, all of them might appear to be slow. 大多数情况下,使用自己的分配线程算法,线程池将更好地执行任务。In most cases the thread pool will perform better with its own algorithm for allocating threads.

属性

CompletedWorkItemCount

获取迄今为止已处理的工作项数。Gets the number of work items that have been processed so far.

PendingWorkItemCount

获取当前已加入处理队列的工作项数。Gets the number of work items that are currently queued to be processed.

ThreadCount

获取当前存在的线程池线程数。Gets the number of thread pool threads that currently exist.

方法

BindHandle(IntPtr)

将操作系统句柄绑定到 ThreadPoolBinds an operating system handle to the ThreadPool.

BindHandle(SafeHandle)

将操作系统句柄绑定到 ThreadPoolBinds an operating system handle to the ThreadPool.

GetAvailableThreads(Int32, Int32)

检索由 GetMaxThreads(Int32, Int32) 方法返回的最大线程池线程数和当前活动线程数之间的差值。Retrieves the difference between the maximum number of thread pool threads returned by the GetMaxThreads(Int32, Int32) method, and the number currently active.

GetMaxThreads(Int32, Int32)

检索可以同时处于活动状态的线程池请求的数目。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.

GetMinThreads(Int32, Int32)

发出新的请求时,在切换到管理线程创建和销毁的算法之前检索线程池按需创建的线程的最小数量。Retrieves the minimum number of threads the thread pool creates on demand, as new requests are made, before switching to an algorithm for managing thread creation and destruction.

QueueUserWorkItem(WaitCallback)

将方法排入队列以便执行。Queues a method for execution. 此方法在有线程池线程变得可用时执行。The method executes when a thread pool thread becomes available.

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.

QueueUserWorkItem<TState>(Action<TState>, TState, Boolean)

Action<T> 委托指定的方法排入队列以便执行,并提供该方法使用的数据。Queues a method specified by an Action<T> delegate for execution, and provides data to be used by the method. 此方法在有线程池线程变得可用时执行。The method executes when a thread pool thread becomes available.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

注册一个等待 WaitHandle 的委托,并指定一个 32 位有符号整数来表示超时值(以毫秒为单位)。Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

注册一个等待 WaitHandle 的委托,并指定一个 64 位有符号整数来表示超时值(以毫秒为单位)。Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)

注册一个等待 WaitHandle 的委托,并指定一个 TimeSpan 值来表示超时时间。Registers a delegate to wait for a WaitHandle, specifying a TimeSpan value for the time-out.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

指定表示超时(以毫秒为单位)的 32 位无符号整数,注册一个委托等待 WaitHandleRegisters a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds.

SetMaxThreads(Int32, Int32)

设置可以同时处于活动状态的线程池的请求数目。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.

SetMinThreads(Int32, Int32)

发出新的请求时,在切换到管理线程创建和销毁的算法之前设置线程池按需创建的线程的最小数量。Sets the minimum number of threads the thread pool creates on demand, as new requests are made, before switching to an algorithm for managing thread creation and destruction.

UnsafeQueueNativeOverlapped(NativeOverlapped*)

将重叠的 I/O 操作排队以便执行。Queues an overlapped I/O operation for execution.

UnsafeQueueUserWorkItem(IThreadPoolWorkItem, Boolean)

将指定的工作项对象排队到线程池。Queues the specified work item object to the thread pool.

UnsafeQueueUserWorkItem(WaitCallback, Object)

将指定的委托排队到线程池,但不会将调用堆栈传播到辅助线程。Queues the specified delegate to the thread pool, but does not propagate the calling stack to the worker thread.

UnsafeQueueUserWorkItem<TState>(Action<TState>, TState, Boolean)

Action<T> 委托指定的方法排入队列以便执行,并指定包含该方法使用的数据的对象。Queues a method specified by an Action<T> delegate for execution, and specifies an object containing data to be used by the method. 此方法在有线程池线程变得可用时执行。The method executes when a thread pool thread becomes available.

UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

注册一个等待 WaitHandle 的委托,并使用一个 32 位带符号整数来表示超时时间(以毫秒为单位)。Registers a delegate to wait for a WaitHandle, using a 32-bit signed integer for the time-out in milliseconds. 此方法不将调用堆栈传播到辅助线程。This method does not propagate the calling stack to the worker thread.

UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

注册一个等待 WaitHandle 的委托,并指定一个 64 位有符号整数来表示超时值(以毫秒为单位)。Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds. 此方法不将调用堆栈传播到辅助线程。This method does not propagate the calling stack to the worker thread.

UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)

注册一个等待 WaitHandle 的委托,并指定一个 TimeSpan 值来表示超时时间。此方法不将调用堆栈传播到辅助线程。Registers a delegate to wait for a WaitHandle, specifying a TimeSpan value for the time-out. This method does not propagate the calling stack to the worker thread.

UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

指定表示超时(以毫秒为单位)的 32 位无符号整数,注册一个委托等待 WaitHandleRegisters a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds. 此方法不将调用堆栈传播到辅助线程。This method does not propagate the calling stack to the worker thread.

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅