下面我們就動手來建立一個線程,使用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();
//這裡建立一個線程,使之執行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異常
以上就是C#的多線程機制初探(2)的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!