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

C# ThreadPool之QueueUserWorkItem使用案例詳解

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

先看代碼:

//設置可以同時處于活動狀態(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"));
};

上面代碼先設置線程池中最大并發(fā)量為8個,然后通過QueueUserWorkItem向線程池中添加11個方法,運行,輸出結果:

可以看出,先運行了8個,當有一個任務結束后線程池中有空閑線程時,排隊的下一個任務才會執(zhí)行,

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

{
    //設置可以同時處于活動狀態(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"));
    };
}

運行結果:

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

總結一下

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

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

相關文章

最新評論