線程池維護一個請求隊列,線程池的代碼從隊列提取任務,而後委派給線程池的一個線程執行,線程執行完不會被當即銷燬,這樣既能夠在後臺執行任務,又能夠減小線程建立和銷燬所帶來的開銷多線程
線程池線程默認爲後臺線程(IsBackground)異步
namespace Test { class Program { static void Main(string[] args) { //將工做項加入到線程池隊列中,這裏能夠傳遞一個線程參數 ThreadPool.QueueUserWorkItem(TestMethod, "Hello"); Console.ReadKey(); } public static void TestMethod(object data) { string datastr = data as string; Console.WriteLine(datastr); } } }
委託的異步調用:BeginInvoke() 和 EndInvoke()函數
/**/ using System.Threading; namespace 多線程 { public delegate string MyDelegate(object data); class Program { static void Main(string[] args) { MyDelegate mDelegate = new MyDelegate(TestMethod); IAsyncResult result = mDelegate.BeginInvoke("Thread Param", TestCallback, "Callback Param"); var strResult = mDelegate.EndInvoke(result); Console.ReadKey(); } /// <summary> /// 線程函數 /// </summary> /// <param name="data"></param> /// <returns></returns> public static string TestMethod(object data) { var strData = data as string; return strData; } /// <summary> /// 異步回調函數 /// </summary> /// <param name="data"></param> public static void TestCallback(IAsyncResult data) { Console.WriteLine(data.AsyncState); } } }
using System.Timers;//多線程計時器 namespace 定時器 { class Program { static void Main(string[] args) { Timer tmr = new Timer(); tmr.Interval = 1000; tmr.Elapsed+=tmr_Elapsed; tmr.Start(); Console.ReadLine(); tmr.Stop(); tmr.AutoReset = true;////設置是執行一次(false)仍是一直執行(true) } private static void tmr_Elapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("Tick..."); } } }