System.Threading.TheadPool 可以看做是若干個Thread組成的隊列。
一個進程僅有一個ThreadPool,所以ThreadPool類中都是靜態方法。ThreadPool會在首次調用注冊線程方法時被創建。(ThreadPool.QueueUserWorkItem、ThreadPool.RegisterWaitForSingleObject等)。
一個ThreadPool裡面注冊的線程擁有默認的堆棧大小,默認的優先級。並且,他們都存在於多線程空間(Multithreaded apartment)中。
ThreadPool中的Thread不能手動取消,也不用手動開始。所以ThreadPool並不適用比較長的線程。你要做的只是把一個WaitCallback委托塞給ThreadPool,然後剩下的工作將由系統自動完成。系統會在ThreadPool的線程隊列中一一啟動線程。
當線程池滿時,多余的線程會在隊列裡排隊,當線程池空閒時,系統自動掉入排隊的線程,以保持系統利用率。
在以下情況中不宜使用ThreadPool而應該使用單獨的Thread:
1,需要為線程指定詳細的優先級
2,線程執行需要很長時間
3,需要把線程放在單獨的線程apartment中
4,在線程執行中需要對線程操作,如打斷,掛起等。
Threadpool中線程的注冊:
委托:
ThreadPool.QueueUserWorkItem(
Timer:
ThreadPool.RegisterWaitForSingleObject(
AutoResetEventObject,
代碼示例:
//Coding by zhl
using System;
using System.Threading;

public class TestThreadPool ...{
//Entry of Application
public static void Main() ...{
//Declare delegate WaitCallback
WaitCallback wc = new WaitCallback(run);
for(int i = 0; i < 10; i++)
//Assign thread in the thread pool
ThreadPool.QueueUserWorkItem(wc,i);
while (true)
if(Console.ReadLine().ToLower()=="exit") break;
}
//Function which is pointed by delegate WaitCallback
public static void run(object state) ...{
Console.WriteLine("Starting...");
Console.WriteLine("Thread {0} is started.",state);
Thread.Sleep(10000);
Console.WriteLine("Thread {0} is shutted down.",state);
}
}new WaitOrTimerCallback(FunctionCall),