調(diào)用C# Thread.Start()方法
C#語言還是比較常見的東西,這里我們主要介紹調(diào)用C# Thread.Start()方法,包括介紹XX等方面。
我們首先創(chuàng)建一個線程,使用Thread類創(chuàng)建線程時,只需提供線程入口即可。(線程入口使程序知道該讓這個線程干什么事)
在C#中,線程入口是通過ThreadStart代理(delegate)來提供的,你可以把ThreadStart理解為一個函數(shù)指針,指向線程要執(zhí)行的函數(shù),當調(diào)用C# Thread.Start()方法后,線程就開始執(zhí)行ThreadStart所代表或者說指向的函數(shù)。
打開你的VS.net,新建一個控制臺應(yīng)用程序(Console Application),編寫完全控制一個線程的代碼示例:
- using System;
 - using System.Threading;
 - namespace ThreadTest
 - {
 - public class Alpha
 - {
 - public void Beta()
 - {
 - while (true)
 - {
 - Console.WriteLine("Alpha.Beta is running in its own thread.");
 - }
 - }
 - };
 - public class Simple
 - {
 - public static int Main()
 - {
 - Console.WriteLine("Thread Start/Stop/Join Sample");
 - Alpha oAlpha = new Alpha();
 - file://這里創(chuàng)建一個線程,使之執(zhí)行Alpha類的Beta()方法
 - Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
 - oThread.Start();
 - while (!oThread.IsAlive)
 - Thread.Sleep(1);
 - oThread.Abort();
 - oThread.Join();
 - Console.WriteLine();
 - Console.WriteLine("Alpha.Beta has finished");
 - try
 - {
 - Console.WriteLine("Try to restart the Alpha.Beta thread");
 - oThread.Start();
 - }
 - catch (ThreadStateException)
 - {
 - Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
 - Console.WriteLine("Expected since aborted threads cannot be restarted.");
 - Console.ReadLine();
 - }
 - return 0;
 - }
 - }
 - }
 
這段程序包含兩個類Alpha和Simple,在創(chuàng)建線程oThread時我們用指向Alpha.Beta()方法的初始化了ThreadStart代理(delegate)對象,當我們創(chuàng)建的線程oThread調(diào)用C# Thread.Start()方法啟動時,實際上程序運行的是Alpha.Beta()方法:
- Alpha oAlpha = new Alpha();
 - Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
 - oThread.Start();
 
然后在Main()函數(shù)的while循環(huán)中,我們使用靜態(tài)方法Thread.Sleep()讓主線程停了1ms,這段時間CPU轉(zhuǎn)向執(zhí)行線程 oThread。然后我們試圖調(diào)用Thread.Abort()方法終止線程oThread,注意后面的 oThread.Join(),Thread.Join()方法使主線程等待,直到oThread線程結(jié)束。你可以給Thread.Join()方法指定一個int型的參數(shù)作為等待的最長時間。之后,我們試圖用C# Thread.Start()方法重新啟動線程oThread,但是顯然Abort()方法帶來的后果是不可恢復(fù)的終止線程,所以***程序會拋出ThreadStateException異常。
【編輯推薦】















 
 
 

 
 
 
 