標籤:
道理非常簡單。
1 Thread mThread = null; 2 int mnCnt = 50; 3 4 public FrmTest() 5 { 6 InitializeComponent(); 7 8 mThread = new Thread(new ThreadStart( 9 delegate10 {11 while (true)12 {13 Thread.Sleep(100);14 Debug.WriteLine(Environment.TickCount.ToString());15 16 if (mnCnt-- < 0)17 {18 break;19 }20 }21 //方式1:22 if (true)23 {24 Stop();25 }26 27 //方式2:28 if (false)29 {30 Thread t = new Thread(new ThreadStart(31 delegate32 {33 Stop();34 }));35 t.Start();36 }37 }));38 mThread.Start();39 }40 41 private void Stop()42 {43 try44 {45 mThread.Abort();46 }47 catch (Exception ex)48 {49 Debug.WriteLine(ex.ToString());50 51 //使用方式1時,當執行到這裡時,下面代碼不會再執行52 }53 54 //其他代碼55 //...56 Debug.WriteLine("停止");57 }
//在 System.Threading.ThreadAbortException 中第一次偶然出現的“mscorlib.dll”類型的異常
//“Test201102051346.vshost.exe”(託管(v4.0.30319)): 已載入“C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_zh-Hans_b77a5c561934e089\mscorlib.resources.dll”
//System.Threading.ThreadAbortException: 正在中止線程。
//在 System.Threading.Thread.AbortInternal()
//在 System.Threading.Thread.Abort()
//在 Test201102051346.FrmTest.Stop() 位置 D:\Users\Wagwei\Desktop\Test201102051346\Test201102051346\FrmTest.cs:行號 62
//在 System.Threading.ThreadAbortException 中第一次偶然出現的“Test201102051346.exe”類型的異常
//“System.Threading.ThreadAbortException”類型的異常在 Test201102051346.exe 中發生,但未在使用者代碼中進行處理
使用線程時需要注意的地方