欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# ThreadPool之QueueUserWorkItem使用案例詳解

 更新時間:2021年08月28日 16:28:32   作者:小目標(biāo)一個億  
這篇文章主要介紹了C# ThreadPool之QueueUserWorkItem使用案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

先看代碼:

//設(shè)置可以同時處于活動狀態(tài)的線程池的請求數(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個,然后通過QueueUserWorkItem向線程池中添加11個方法,運(yùn)行,輸出結(jié)果:

可以看出,先運(yùn)行了8個,當(dāng)有一個任務(wù)結(jié)束后線程池中有空閑線程時,排隊(duì)的下一個任務(wù)才會執(zhí)行,

把最大并發(fā)量改成9試試:

{
    //設(shè)置可以同時處于活動狀態(tài)的線程池的請求數(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é)果:

果然沒錯,這次是先執(zhí)行9個,當(dāng)有空閑線程時再執(zhí)行下一個

總結(jié)一下

QueueUserWorkItem:將方法排入隊(duì)列以便執(zhí)行。 此方法在有線程池線程變得可用時執(zhí)行。

到此這篇關(guān)于C# ThreadPool之QueueUserWorkItem使用案例詳解的文章就介紹到這了,更多相關(guān)C# ThreadPool之QueueUserWorkItem內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論