1. 引言
近來在研究c#多線程編程碰到了線程池的概念。不懂,我搜,于是在msdn和csdn上尋尋覓覓一番終于搞明白,“緣”來如此,安裝本人理解修改后寫下這篇文章,希望對后來者有所幫助。
2. 線程池的概念
可以使用線程池來根據應用程序的需要更為有效地利用多個線程。許多應用程序使用多個線程,但這些線程經常在休眠狀態中耗費大量的時間來等待事件發生,編程者手動管理多個線程也是一件比較麻煩的事情。事實上,使用線程池就是為應用程序提供一個由系統管理的輔助線程池,從而使您可以集中精力于應用程序任務而不是線程管理。
實際上,如果要執行一些需要多個線程的較短任務,則使用 threadpool 類是利用多個線程的最方便且最好的方法。使用線程池能夠優化這些任務的執行過程,從而提高吞吐量,它不僅能夠使系統針對此進程優化該執行過程,而且還能夠使系統針對計算機上的其他進程優化該執行過程,即使您的應用程序對這些進程一無所知,系統也能做到這一點。使用線程池使系統能夠在考慮到計算機上的所有當前進程后對線程時間片進行優化。
.net framework 出于以下幾個目的使用線程池:異步調用、system.net 套接字連接、異步 i/o 完成以及計時器與注冊的等待操作等等。
每個進程只有一個threadpool對象。線程池在您第一次調用 threadpool.queueuserworkitem 時創建,或者在一個計時器或注冊的等待操作將一個回調方法排入隊列時創建。一個線程監視所有已排隊到線程池中的任務。當某項任務完成后,線程池中的線程將執行相應的回調方法。在對一個工作項進行排隊之后將無法取消它。
通過調用system.threading.threadpool.queueuserworkitem(waitcallback)來使用線程池,waitcallback是要添加到隊列中的方法。也可以通過使用system.threading.threadpool.registerwaitforsingleobject()并傳遞 waithandle來將與等待操作相關的工作項排隊到線程池中。在這兩種情況下,線程池都使用或創建一個后臺線程來調用回調方法。
在以下情況,適合于創建并管理自己的線程而不是使用 threadpool:
1)如果您需要使一個任務具有特定的優先級。
2)如果您具有可能會長時間運行(并因此阻塞其他任務)的任務。
3)如果您需要將線程放置到單線程單元中(所有 threadpool 線程均處于多線程單元中)。
4)如果您需要與線程關聯的永久標識。例如,您可能想使用專用線程來中止該線程、將其掛起或按名稱發現它。
3. 示例代碼
c#
//copyright (c) microsoft corporation. all rights reserved.
//這個示例是用多線程來計算斐波納契數列(一種整數數列, 其中每數等于前面兩數之和).
using system;
using system.threading;
// the fibonacci class provides an interface for using an auxiliary
// thread to perform the lengthy fibonacci(n) calculation.
// n is provided to the fibonacci constructor, along with an
// event that the object signals when the operation is complete.
// the result can then be retrieved with the fibofn property.
public class fibonacci
{
public fibonacci(int n, manualresetevent doneevent)
{
_n = n;
_doneevent = doneevent;
}
// wrapper method for use with thread pool.
public void threadpoolcallback(object threadcontext)
{
int threadindex = (int)threadcontext;
console.writeline("thread {0} started...", threadindex);
_fibofn = calculate(_n);
console.writeline("thread {0} result calculated...", threadindex);
_doneevent.set();
}
// recursive method that calculates the nth fibonacci number.
public int calculate(int n)
{
if (n <= 1)
{
return n;
}
else
{
return calculate(n - 1) + calculate(n - 2);
}
}
public int n { get { return _n; } }
private int _n;
public int fibofn { get { return _fibofn; } }
private int _fibofn;
manualresetevent _doneevent;
}
public class threadpoolexample
{
static void main()
{
const int fibonaccicalculations = 10;
// one event is used for each fibonacci object
manualresetevent[] doneevents = new manualresetevent[fibonaccicalculations];
fibonacci[] fibarray = new fibonacci[fibonaccicalculations];
random r = new random();
// configure and launch threads using threadpool: 按次序把10個線程放入線程池
// queueuserworkitem方法有兩個版本,詳情請查msdn:
//threadpool.queueuserworkitem (waitcallback)
//threadpool.queueuserworkitem (waitcallback, object)
//i是給回調方法用的帶數據對象(就是參數)即i作為參數傳給了threadpoolcallback()函數
console.writeline("launching {0} tasks...", fibonaccicalculations);
for (int i = 0; i < fibonaccicalculations; i++)
{
doneevents[i] = new manualresetevent(false);
fibonacci f = new fibonacci(r.next(20,40), doneevents[i]);
fibarray[i] = f;
threadpool.queueuserworkitem(f.threadpoolcallback, i);
}
// wait for all threads in pool to calculation...
waithandle.waitall(doneevents);
console.writeline("calculations complete.");
// display the results...
for (int i= 0; i<fibonaccicalculations; i++)
{
fibonacci f = fibarray[i];
console.writeline("fibonacci({0}) = {1}", f.n, f.fibofn);
}
}
}
參考文獻
[1]http://msdn.microsoft.com/library/chs/default.asp?url=/library/chs/cpguide/html/cpconthreadpooling.asp
[2] http://msdn2.microsoft.com/en-us/library/w1w6424a(vs.80).aspx
[3] vs2005 幫助文檔
新聞熱點
疑難解答