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:

  • 當您建立TaskTask<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 的 unmanaged 程式碼可以使用變更的執行緒集區大小CorSetMaxThreads函式,定義於 mscoree.h 檔案。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
PendingWorkItemCount PendingWorkItemCount PendingWorkItemCount PendingWorkItemCount
ThreadCount ThreadCount ThreadCount ThreadCount

方法

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)
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.

另請參閱