C#的多線程機制初探(2)
下面我們就動手來創建一個線程,使用Thread類創建線程時,只需提供線程入口即可。線程入口使程序知道該讓這個線程干什麼事,在C#中,線程入口是通過ThreadStart代理(delegate)來提供的,你可以把ThreadStart理解為一個函數指針,指向線程要執行的函數,當調用Thread.Start()方法後,線程就開始執行ThreadStart所代表或者說指向的函數。
打開你的VS.net,新建一個控制台應用程序(Console Application),下面這些代碼將讓你體味到完全控制一個線程的無窮樂趣!
//ThreadTest.cs
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://這裡創建一個線程,使之執行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,在創建線程oThread時我們用指向Alpha.Beta()方法的初始化了ThreadStart代理(delegate)對象,當我們創建的線程oThread調用oThread.Start()方法啟動時,實際上程序運行的是Alpha.Beta()方法:
Alpha oAlpha = new Alpha();
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
oThread.Start();
然後在Main()函數的while循環中,我們使用靜態方法Thread.Sleep()讓主線程停了1ms,這段時間CPU轉向執行線程oThread。然後我們試圖用Thread.Abort()方法終止線程oThread,注意後面的oThread.Join(),Thread.Join()方法使主線程等待,直到oThread線程結束。你可以給Thread.Join()方法指定一個int型的參數作為等待的最長時間。之後,我們試圖用Thread.Start()方法重新啟動線程oThread,但是顯然Abort()方法帶來的後果是不可恢復的終止線程,所以最後程序會拋出ThreadStateException異常。