進程和線程
進程:進程包含資源,例如windows控制代碼,檔案系統控制代碼或者其他核心對象,每個進程都分配了虛擬記憶體。一個進程至少包含一個線程。作業系統會調度線程。
進程管理的資源套件括虛擬記憶體和windows控制代碼。
線程: 都有自己的堆棧,但程式碼的記憶體和堆由一個進程內所有的線程共用。
在.NET中,託管的線程由Thread類定義。託管的線程不一定映射為一個作業系統線程。
使用委託建立線程的三種方法
1. Pooling 投票方式
2. WaitHandle 等待控制代碼
3. Asynchronous Call 非同步回調
// 非同步委託樣本// Herbert// 個人學習使用using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Diagnostics;namespace AsyDelegate{ class Program { public delegate int TakesAWhileDelegate(int data, int ms); static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TalesAWhile completed"); return ++data; } public static void Method1() { // 第一種投票方式 // synchronouse method call // TakesAWhile(1, 3000) // Asynchronous by using a delegate // IAsyncResult 可以獲得委託資訊,並驗證委託是否完成了任務 TakesAWhileDelegate dl = TakesAWhile; IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null); while (!ar.IsCompleted) { // do something else in the main thread Console.Write("."); Thread.Sleep(50); } int result = dl.EndInvoke(ar); Console.WriteLine("result: {0}", result); } public static void Method2() { // 第二種等待控制代碼方式 // synchronouse method call // TakesAWhile(1, 3000) // Asynchronous by using a delegate // WaitOne()將一個逾時時間作為可選的第一個參數,定義要等待的最大時間 TakesAWhileDelegate dl = TakesAWhile; IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null); while (true) { // do something else in the main thread Console.Write("."); if (ar.AsyncWaitHandle.WaitOne(50, false)) { Console.WriteLine("Can get the result now"); break; } } int result = dl.EndInvoke(ar); Console.WriteLine("result: {0}", result); } public static void TakesAWhileCompleted(IAsyncResult ar) { // 第三種方式非同步回調 if (ar == null) throw new ArgumentNullException("ar"); TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate; Trace.Assert(d1 != null, "Invalid object type"); int result = d1.EndInvoke(ar); Console.WriteLine("result : {0}", result); } static void Main(string[] args) { Stopwatch sw1 = new Stopwatch(); Console.WriteLine("Method 1 Pooling started:"); sw1.Start(); Program.Method1(); sw1.Stop(); Console.WriteLine(sw1.ElapsedMilliseconds.ToString()); Stopwatch sw2 = new Stopwatch(); Console.WriteLine("Method 2 Wait Handler started:"); sw2.Start(); Program.Method2(); sw2.Stop(); Console.WriteLine(sw2.ElapsedMilliseconds.ToString()); Stopwatch sw3 = new Stopwatch(); Console.WriteLine("Method 3 Asynchronize CallBack started:"); sw3.Start(); TakesAWhileDelegate d1 = TakesAWhile; /* d1.BeginInvoke(1, 3000, ar => { int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); }), null; */ d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(50); } Console.WriteLine(sw3.ElapsedMilliseconds.ToString()); Console.ReadKey(); } }}
通過已耗用時間進行比較, 投票方式和非同步回調比較好用,似乎投票方式效率會低些,而非同步回調效率最高。