1. 程式人生 > >使用線程池

使用線程池

tar thread img static 線程 format bak width work

簡介

創建線程是昂貴的操作,為每一個短暫的異步操作創建線程會產生顯著的開銷。

技術分享圖片

技術分享圖片

在線程池中調用委托

 1 using System;
 2 using System.Threading;
 3 
 4 namespace Chapter3.Recipe1
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             int threadId = 0;
11 
12             RunOnThreadPool poolDelegate = Test;
13 14 var t = new Thread(() => Test(out threadId)); 15 t.Start(); 16 t.Join(); 17 18 Console.WriteLine("Thread id: {0}", threadId); 19 20 //調用BeginInvoke()運行委托,回調函數在異步操作完成後被調用 21 //BeginInvoke()調用後會立即返回,線程池中的工作線程在執行異步操作時,仍允許繼續其他工作。
22 IAsyncResult r = poolDelegate.BeginInvoke(out threadId, Callback, "a delegate asynchronous call"); 23 r.AsyncWaitHandle.WaitOne(); //等待異步操作完成 24 //事實上EndInvoke()會等待異步操作的完成,所以r.AsyncWaitHandle.WaitOne();並不是必要的 25 string result = poolDelegate.EndInvoke(out
threadId, r); 26 //異步操作完成後,回調函數會被放置到線程池中,確切的說是一個工作線程中。 27 Console.WriteLine("Thread pool worker thread id: {0}", threadId); 28 Console.WriteLine(result); 29 30 Thread.Sleep(TimeSpan.FromSeconds(2)); 31 } 32 33 private delegate string RunOnThreadPool(out int threadId); 34 35 private static void Callback(IAsyncResult ar)//回調函數 36 { 37 Console.WriteLine("Starting a callback..."); 38 Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState); 39 Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); 40 Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId); 41 } 42 43 44 private static string Test(out int threadId) 45 { 46 Console.WriteLine("Starting..."); 47 Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); 48 Thread.Sleep(TimeSpan.FromSeconds(2)); 49 threadId = Thread.CurrentThread.ManagedThreadId; 50 return string.Format("Thread pool worker thread id was: {0}", threadId); 51 } 52 } 53 }

技術分享圖片

使用BeginOperationName/EndOperation方法和.NET中的IAsyncResult對象等方式被稱為異步編程模型,這樣的方法對被稱為異步方法。

使用線程池