(一).描述 此示例演示怎樣設(shè)置線程的狀態(tài)(中止,暫停,掛起等) (二).代碼 using System; using
System.Threading;
namespace 管理線程_使線程中止_暫停_掛起等_ { //委托聲明(函數(shù)簽名) delegate string
MyMethodDelegate(); class MyClass { public static void
Method1() { //thread1.Abort();一句中的
Abort會引發(fā)異常System.Threading.ThreadAbortException,其異常作用,,下面會講解 try { int
i; for(i=0;i<10;i++) { Console.WriteLine("Method1 at :"
+ i.ToString()); DelayTime(1);
//延長時間(模擬執(zhí)行任務(wù)) } } catch(System.Threading.ThreadAbortException) { //注意一點,,線程跳出此語句塊后才終止。 //這里可以寫釋放此進程占用的資源代碼,或者其它一些操作,,比如:
在進程結(jié)束前將重要數(shù)據(jù)寫回數(shù)據(jù)庫中 Console.WriteLine("進程1馬上將被強制殺死!"); Thread.ResetAbort();
//取消Abort()操作,我在這里加這句沒用,,反而出現(xiàn)異常了,讀者如果知道,請告訴我怎樣寫才對 } } public
static void Method2() { int
i; for(i=0;i<10;i++) { Console.WriteLine("Method2 at :" +
i.ToString()); DelayTime(1);
//延長時間,,模擬執(zhí)行任務(wù) } } private static void DelayTime(int
n) { DateTime startTime =
DateTime.Now; while(startTime.AddSeconds(n) >
DateTime.Now) { //延長時間,模擬實際中的進程 } }
[STAThread] static void Main(string[] args) {
Thread thread1 = new Thread(new ThreadStart(Method1)); Thread
thread2 = new Thread(new
ThreadStart(Method2)); thread1.Start(); thread2.Start(); thread1.Abort();
//將線程強制終止(殺死)
//thread1.Join的作用是無限制等待thread1終止后,,才執(zhí)行下面的語句,起到與主線程同步的作用. //原因是:
thread1最終是被終止的,,但是thread1一個獨立的線程,它并不會馬上被終止,。 //什么時候用:就拿這里來舉例吧,當thread1占用著一個資源,,當thread1終止后,, //thread2線程馬上也要用此資源,這就要求等待thread1徹底終止并釋放后占用資源后,才能接著執(zhí)行下一句,, //否則線程thread2會找不到此資源,,甚至?xí)l(fā)生異常錯誤!
為了安全起見,一般是要在Abort()方法后面緊跟一個Join()方法的.
//thread1.Suspend();//此方法將線程無限制時間的掛起,相當于無限制時間的暫停線程
//thread1.Resume();
//將正在掛起的進程繼續(xù)執(zhí)行 //Thread.Sleep(1000);//暫停線程1秒鐘,以毫秒為單位暫停. //Thread.ResetAbort();
//取消Abort()操作 //thread1.Interrupt();
//中止線程現(xiàn)在處的狀態(tài),。如果線程由運行轉(zhuǎn)到休眠,,執(zhí)行此句后,會使線程重新返回到運行狀態(tài)
Console.Read(); } } }
本示例代碼已經(jīng)測試,,能夠正常運行!
(三).示例下載 http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar
|