C# ThreadPool之QueueUserWorkItem使用案例詳解

先看代碼:

//設置可以同時處於活動狀態的線程池的請求數目。 
bool pool = ThreadPool.SetMaxThreads(8, 8);
if (pool) {
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數1"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數2"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數3"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數4"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數5"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數6"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數7"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數8"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數9"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數10"));
    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數11"));
};

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

可以看出,先運行瞭8個,當有一個任務結束後線程池中有空閑線程時,排隊的下一個任務才會執行,

把最大並發量改成9試試:

{
    //設置可以同時處於活動狀態的線程池的請求數目。 
    bool pool = ThreadPool.SetMaxThreads(9, 9);
    if (pool) {
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數1"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數2"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數3"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數4"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數5"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數6"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數7"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數8"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數9"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數10"));
        ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("參數11"));
    };
}

運行結果:

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

總結一下

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

到此這篇關於C# ThreadPool之QueueUserWorkItem使用案例詳解的文章就介紹到這瞭,更多相關C# ThreadPool之QueueUserWorkItem內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: