C#多線程ThreadPool線程池詳解
簡單說明一下:
線程池可以看做容納線程的容器;一個應(yīng)用程序最多只能有一個線程池;ThreadPool靜態(tài)類通過QueueUserWorkItem()方法將工作函數(shù)排入線程池; 每排入一個工作函數(shù),就相當(dāng)于請求創(chuàng)建一個線程;
線程池的作用:
1、線程池是為突然大量爆發(fā)的線程設(shè)計的,通過有限的幾個固定線程為大量的操作服務(wù),減少了創(chuàng)建和銷毀線程所需的時間,從而提高效率。
2、如果一個線程的時間非常長,就沒必要用線程池了(不是不能作長時間操作,而是不宜。),況且我們還不能控制線程池中線程的開始、掛起、和中止。
一些使用例子:
實例一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThreadPoolDemo
{
class Program
{
static void Main(string[] args)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestThreadPool),new string[] {"drsw","sfs","sdfs"});
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
string[] arry = state as string[]; //傳過來的參數(shù)值
int workerThreads = 0;
int completionPortThreads = 0;
System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.Write(DateTime.Now.ToString() + "--" + arry[0] + "----workerThreads=" + workerThreads + "----completionPortThreads=" + completionPortThreads);
}
}
}
上述代碼運行結(jié)果:

使用例子二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThreadPoolDemo
{
class Program
{
static void Main(string[] args)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestThreadPool));
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
int workerThreads = 0;
int completionPortThreads = 0;
System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.Write(DateTime.Now.ToString() + "----workerThreads=" + workerThreads + "----completionPortThreads=" + completionPortThreads);
}
}
}
上述代碼運行結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
分享兩種實現(xiàn)Winform程序的多語言支持的多種解決方案
本篇文章主要介紹了分享兩種實現(xiàn)Winform程序的多語言支持的多種解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧。2017-02-02
通過C#實現(xiàn)發(fā)送自定義的html格式郵件
本篇文章主要介紹了通過C#實現(xiàn)發(fā)送自定義的html格式郵件,詳細的介紹了發(fā)送HTML格式郵件的方法,有興趣的可以了解一下。2017-02-02
C# WinForm實現(xiàn)鼠標(biāo)穿透功能
在WinForm開發(fā)時,會用到這樣一個場景,給屏幕增加水印Logo,但不影響畫面的操作,這里就會用到鼠標(biāo)穿透功能,下面我們就來學(xué)習(xí)一下鼠標(biāo)穿透功能的具體實現(xiàn)吧2023-11-11

