ThreadPool ThreadPool ThreadPool ThreadPool Class

定義

提供執行緒的集區,可用來執行工作、張貼工作項目、處理非同步 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
繼承
ThreadPoolThreadPoolThreadPoolThreadPool

範例

在下列範例中,主應用程式執行緒會將名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. ThreadProc方法只會顯示訊息。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:

  • 當您建立或Task 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. 執行緒集區執行緒會從System.Threading.Timer類別執行回呼,並System.Timers.Timer從類別引發事件。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. 您可以藉由將WaitCallback委派傳遞給方法來達到此目的。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. 您可以藉由呼叫QueueUserWorkItem(WaitCallback, Object)方法,將實際的資料傳遞給委派。The actual data can be passed to the delegate by calling the QueueUserWorkItem(WaitCallback, Object) method.

注意

Managed 執行緒集區中的執行緒是背景執行緒。The threads in the managed thread pool are background threads. 亦即,其IsBackground屬性為trueThat is, their IsBackground properties are true. 這表示在ThreadPool所有前景執行緒結束之後,執行緒將不會繼續執行應用程式。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. 您可以使用SetMaxThreads方法來變更執行緒集區中的執行緒數目。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.

警告

您可以使用SetMinThreads方法來增加執行緒的最小數目。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 CompletedWorkItemCount CompletedWorkItemCount CompletedWorkItemCount

取得目前已經處理完成的工作項目數。Gets the number of work items that have been processed so far.

PendingWorkItemCount PendingWorkItemCount PendingWorkItemCount PendingWorkItemCount

取得目前已排入佇列,等待處理的工作項目數。Gets the number of work items that are currently queued to be processed.

ThreadCount ThreadCount ThreadCount ThreadCount

取得目前存在的執行緒集區執行緒數。Gets the number of thread pool threads that currently exist.

方法

BindHandle(IntPtr) BindHandle(IntPtr) BindHandle(IntPtr) BindHandle(IntPtr)

可將作業系統的控制代碼繫結至 ThreadPoolBinds an operating system handle to the ThreadPool.

BindHandle(SafeHandle) BindHandle(SafeHandle) BindHandle(SafeHandle) BindHandle(SafeHandle)

可將作業系統的控制代碼繫結至 ThreadPoolBinds an operating system handle to the ThreadPool.

GetAvailableThreads(Int32, Int32) GetAvailableThreads(Int32, Int32) GetAvailableThreads(Int32, Int32) 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) GetMaxThreads(Int32, Int32) GetMaxThreads(Int32, Int32) 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) GetMinThreads(Int32, Int32) GetMinThreads(Int32, Int32) 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) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback)

將方法排入佇列,以等候執行。Queues a method for execution. 可以使用執行緒集區執行緒時,即可執行這個方法。The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) 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) QueueUserWorkItem<TState>(Action<TState>, TState, Boolean) QueueUserWorkItem<TState>(Action<TState>, TState, Boolean) 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, UInt32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

指定 32 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。Registers a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) 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, Int32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

指定 32 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。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) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean) RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

指定 64 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds.

SetMaxThreads(Int32, Int32) SetMaxThreads(Int32, Int32) SetMaxThreads(Int32, Int32) 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) SetMinThreads(Int32, Int32) SetMinThreads(Int32, Int32) 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*) UnsafeQueueNativeOverlapped(NativeOverlapped*) UnsafeQueueNativeOverlapped(NativeOverlapped*) UnsafeQueueNativeOverlapped(NativeOverlapped*)

將重疊的 I/O 作業排入佇列,以等候執行。Queues an overlapped I/O operation for execution.

UnsafeQueueUserWorkItem(IThreadPoolWorkItem, Boolean) UnsafeQueueUserWorkItem(IThreadPoolWorkItem, Boolean) UnsafeQueueUserWorkItem(IThreadPoolWorkItem, Boolean) UnsafeQueueUserWorkItem(IThreadPoolWorkItem, Boolean)

將指定的工作項目物件排入執行緒集區。Queues the specified work item object to the thread pool.

UnsafeQueueUserWorkItem(WaitCallback, Object) UnsafeQueueUserWorkItem(WaitCallback, Object) UnsafeQueueUserWorkItem(WaitCallback, Object) 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) UnsafeQueueUserWorkItem<TState>(Action<TState>, TState, Boolean) UnsafeQueueUserWorkItem<TState>(Action<TState>, TState, Boolean) 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, TimeSpan, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean) 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, Int32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

使用 32 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。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) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

指定 64 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。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, UInt32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean) UnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

指定 32 位元帶正負號的整數表示逾時值 (以毫秒為單位),藉此註冊要等候 WaitHandle 的委派。Registers 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.

另請參閱