C#語言還是比較常見的東西,這里我們主要介紹調(diào)用C# Thread.Start()方法,包括介紹XX等方面。
我們首先創(chuàng)建一個(gè)線程,使用Thread類創(chuàng)建線程時(shí),只需提供線程入口即可。(線程入口使程序知道該讓這個(gè)線程干什么事)
在C#中,線程入口是通過ThreadStart代理(delegate)來提供的,你可以把ThreadStart理解為一個(gè)函數(shù)指針,指向線程 要執(zhí)行的函數(shù),當(dāng)調(diào)用C# Thread.Start()方法后,線程就開始執(zhí)行ThreadStart所代表或者說指向的函數(shù)。
打開你的VS.net,新建一個(gè)控制臺(tái)應(yīng)用程序(Console Application),編寫完全控制一個(gè)線程的代碼示例:
- 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)建一個(gè)線程,使之執(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;
- }
- }
- }
這段程序包含兩個(gè)類Alpha和Simple,在創(chuàng)建線程oThread時(shí)我們用指向Alpha.Beta()方法的初始化了 ThreadStart代理(delegate)對(duì)象,當(dāng)我們創(chuàng)建的線程oThread調(diào)用C# Thread.Start()方法啟動(dòng)時(shí),實(shí)際上程序運(yùn)行的是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,這段時(shí)間CPU轉(zhuǎn)向執(zhí)行線程 oThread。然后我們?cè)噲D調(diào)用Thread.Abort()方法終止線程oThread,注意后面的 oThread.Join(),Thread.Join()方法使主線程等待,直到oThread線程結(jié)束。你可以給Thread.Join()方法指定 一個(gè)int型的參數(shù)作為等待的最長時(shí)間。之后,我們?cè)噲D用C# Thread.Start()方法重新啟動(dòng)線程oThread,但是顯然Abort()方法帶來的后果是不可恢復(fù)的終止線程,所以最后程序會(huì)拋出 ThreadStateException異常。
聯(lián)系客服