C# ThreadPool之QueueUserWorkItem使用案例詳解
先看代碼:
//設(shè)置可以同時(shí)處于活動(dòng)狀態(tài)的線程池的請(qǐng)求數(shù)目。
bool pool = ThreadPool.SetMaxThreads(8, 8);
if (pool) {
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)1"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)2"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)3"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)4"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)5"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)6"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)7"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)8"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)9"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)10"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)11"));
};
上面代碼先設(shè)置線程池中最大并發(fā)量為8個(gè),然后通過QueueUserWorkItem向線程池中添加11個(gè)方法,運(yùn)行,輸出結(jié)果:

可以看出,先運(yùn)行了8個(gè),當(dāng)有一個(gè)任務(wù)結(jié)束后線程池中有空閑線程時(shí),排隊(duì)的下一個(gè)任務(wù)才會(huì)執(zhí)行,
把最大并發(fā)量改成9試試:
{
//設(shè)置可以同時(shí)處于活動(dòng)狀態(tài)的線程池的請(qǐng)求數(shù)目。
bool pool = ThreadPool.SetMaxThreads(9, 9);
if (pool) {
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)1"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)2"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)3"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)4"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)5"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)6"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)7"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)8"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)9"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)10"));
ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數(shù)11"));
};
}
運(yùn)行結(jié)果:

果然沒錯(cuò),這次是先執(zhí)行9個(gè),當(dāng)有空閑線程時(shí)再執(zhí)行下一個(gè)
總結(jié)一下
QueueUserWorkItem:將方法排入隊(duì)列以便執(zhí)行。 此方法在有線程池線程變得可用時(shí)執(zhí)行。
到此這篇關(guān)于C# ThreadPool之QueueUserWorkItem使用案例詳解的文章就介紹到這了,更多相關(guān)C# ThreadPool之QueueUserWorkItem內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 批量生成隨機(jī)密碼必須包含數(shù)字和字母并用加密算法加密
這篇文章主要介紹了C# 批量生成隨機(jī)密碼必須包含數(shù)字和字母并用加密算法加密,需要的朋友參考下2017-01-01
C#實(shí)現(xiàn)JSON和對(duì)象之間互相轉(zhuǎn)換功能示例
這篇文章主要介紹了C#實(shí)現(xiàn)JSON和對(duì)象之間互相轉(zhuǎn)換功能,結(jié)合實(shí)例形式較為詳細(xì)的分析了C#實(shí)現(xiàn)對(duì)象與json之間相互轉(zhuǎn)換的操作技巧,需要的朋友可以參考下2017-09-09

