溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中ThreadPool之QueueUserWorkItem怎么用

發(fā)布時間:2021-08-30 09:37:57 來源:億速云 閱讀:282 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)C#中ThreadPool之QueueUserWorkItem怎么用的內(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個方法,運行,輸出結(jié)果:

C#中ThreadPool之QueueUserWorkItem怎么用

可以看出,先運行了8個,當(dāng)有一個任務(wù)結(jié)束后線程池中有空閑線程時,排隊的下一個任務(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"));
    };
}

運行結(jié)果:

C#中ThreadPool之QueueUserWorkItem怎么用

感謝各位的閱讀!關(guān)于“C#中ThreadPool之QueueUserWorkItem怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI