一、Windows為什么要支持線程
Microsoft設(shè)計(jì)OS內(nèi)核時(shí),他們決定在一個(gè)進(jìn)程(public sealed class Thread : CriticalFinalizerobject,... { public Thread(ParameterizedThreadStart start); //這里沒(méi)有列出不常用的構(gòu)造器}start參數(shù)標(biāo)識(shí)專用線程要執(zhí)行的方法,這個(gè)方法必須和ParameterizedThreadStart委托的簽名匹配。
delegate void ParameterizedThreadStart(Oject obj);構(gòu)造Thread對(duì)象是一個(gè)輕量級(jí)操作,因?yàn)樗⒉粚?shí)際創(chuàng)建一個(gè)操作系統(tǒng)線程。要實(shí)際創(chuàng)建操作系統(tǒng)線程,并讓它開(kāi)始執(zhí)行回調(diào)方法,必須調(diào)用Thread的Start方法,向它傳遞要作為回調(diào)方法的實(shí)參傳遞的對(duì)象(狀態(tài))。以下代碼演示了如何創(chuàng)建一個(gè)專用線程,并讓它異步調(diào)用一個(gè)方法:
internal static class FirstThread { public static void Go() { Console.WriteLine("Main thread: starting a dedicated thread " + "to do an asynchronous Operation"); Thread dedicatedThread = new Thread(ComputeBoundOp); dedicatedThread.Start(5); Console.WriteLine("Main thread: Doing other work here..."); Thread.Sleep(10000); // 模擬做其它工作(10 秒鐘) dedicatedThread.Join(); // 等待線程終止 Console.ReadLine(); } // 這個(gè)方法的前面必須和ParametizedThreadStart委托匹配 private static void ComputeBoundOp(Object state) { // 這個(gè)方法由一個(gè)專用線程執(zhí)行 Console.WriteLine("In ComputeBoundOp: state={0}", state); Thread.Sleep(1000); // 模擬其它任務(wù)(1 秒鐘) // 這個(gè)方法返回后,專用線程將終止 }} 在我的機(jī)器上編譯運(yùn)行,可能得到以下結(jié)果:Main thread: starting a dedicated thread to do an asynchronous operationMain thread: Doing other work here...In ComputeBoundOp: state=5 但有的時(shí)候運(yùn)行上述代碼,也可能得到以下結(jié)果,因?yàn)槲覠o(wú)法控制Windows對(duì)兩個(gè)線程進(jìn)行調(diào)度的方式:Main thread: starting a dedicated thread to do an asynchronous operationIn ComputeBoundOp: state=5Main thread: Doing other work here... 注意Go()方法調(diào)用的Join。Join方法造成調(diào)用線程阻塞當(dāng)前執(zhí)行的任何代碼,直到dedicatedThread所代表的那個(gè)線程銷毀或終止。六、使用線程的理由使用線程有以下三方面的理由: