天天看點

CLR線程、線程池、任務的這些事

CLR使用的是Windows的線程處理能力,目前的CLR實作一個CLR線程對應于一個Windows線程

System.Threading.Thread

CLR線程池

建立和銷毀線程是一個昂貴的操作,要耗費大量時間、資源,對性能也有影響。為改善這個情況,CLR包含了代碼來管理它的線程池。可将線程池想象成可由你的程式使用的一個線程集合,每個CLR一個線程池,這個線程池可由CLR控制的所有AppDomian共享。如果一個程序加載了多個CLR,每個CLR都有自己的線程池。

執行上下文

每個線程都關聯一個執行上下文結構,包括:安全設定(Thread.Principal Windows身份)、宿主設定(System.Threading.HostExecutionContextManager)、邏輯調用上下文資料(System.Runtime.Remoting.Messaging.CallContext的LogicSetData和LogicGetData)

預設情況下,CLR自動造成初始線程的執行上下文複制到任何輔助線程,如果需要控制上下文的複制問題,可使用System.Threading.ExecutionContext類,如:

     // Put some data into the Main thread’s logical call context

        CallContext.LogicalSetData("Name", "Jeffrey");

        // Initiate some work to be done by a thread pool thread

        // The thread pool thread can access the logical call context data 

        ThreadPool.QueueUserWorkItem(

           state => Console.WriteLine("Name={0}", CallContext.LogicalGetData("Name")));

        // Suppress the flowing of the Main thread’s execution context

        ExecutionContext.SuppressFlow();

        // The thread pool thread can NOT access the logical call context data

        // Restore the flowing of the Main thread’s execution context in case 

        // it employs more thread pool threads in the future

        ExecutionContext.RestoreFlow();

.net提供了标準的取消操作模式

ThreadPool.QueueUserWorkItem雖然簡單,擔憂如下限制:

Ø  沒有内建的機制知道操作什麼時候完成

Ø  沒有内建的機制在操作完成時獲得一個傳回值

System.Threading.Tasks下的類型可解決這個問題

一個任務完成時自動啟動另一個新任務

Task.ContinueWith

任務可以啟動子任務

<b>任務工廠</b>

<b></b>

         有時,可能需要建立一組Task對象來共享相同的狀态,為了避免機械的将相同的參數傳給每個Task的構造器,可以建立一個任務工廠來封裝通用的狀态。

參考

Clr Via C# 25 26章

<a href="http://transbot.blog.163.com/">http://transbot.blog.163.com</a>

<a href="http://ys-f.ys168.com/?CLR_via_CSharp_3rd_Edition_Code_by_Jeffrey_Richter.zip_55bism1e0e7bkisjthit2bso0cm5bs4bs1b5bktnql0c0bu22f05f12z">http://ys-f.ys168.com/?CLR_via_CSharp_3rd_Edition_Code_by_Jeffrey_Richter.zip_55bism1e0e7bkisjthit2bso0cm5bs4bs1b5bktnql0c0bu22f05f12z</a>