在使用線程時,如果線程還未結束直接退出線程很有可能會導致數據丟失。 Thread.Sleep(500);//500毫秒後結束線程 th.Abort(); 線上程啟動500毫秒後,關閉線程 WriteMessage("線程結束工作.", ConsoleColor.Yellow, ConsoleColo ...
在使用線程時,如果線程還未結束直接退出線程很有可能會導致數據丟失。
class threadAbort { static void Main(string[] args) { WriteMessage("主線程開始工作", ConsoleColor.White, ConsoleColor.White); Thread th = new Thread(new ThreadStart(TestTry)); th.Start(); Thread.Sleep(500);//500毫秒後結束線程 th.Abort(); th.Join(); WriteMessage("主線程結束工作" + th.ThreadState.ToString(), ConsoleColor.White, ConsoleColor.White); Console.ReadKey(); } private static void TestTry() { try { for (int i = 0; i < 10; i++) { WriteMessage("線程正在工作中"+i.ToString(), ConsoleColor.Green, ConsoleColor.White); Thread.Sleep(100); } } catch (ThreadAbortException ex) { WriteMessage("線程錯誤信息:" + ex.Message, ConsoleColor.Red, ConsoleColor.White); } finally { WriteMessage("線程退出。。", ConsoleColor.Blue, ConsoleColor.White); } //如果線程未結束,直接Abort線程,下麵語句將不會被執行。 WriteMessage("線程結束工作.", ConsoleColor.Yellow, ConsoleColor.White); } public static void WriteMessage(string message, ConsoleColor writeColor, ConsoleColor backColor) { Console.ForegroundColor = writeColor; Console.WriteLine(message); //Console.BackgroundColor = backColor; } }
Thread.Sleep(500);//500毫秒後結束線程
th.Abort();
線上程啟動500毫秒後,關閉線程
WriteMessage("線程結束工作.", ConsoleColor.Yellow, ConsoleColor.White);
將不會被執行
如果註釋//th.Abort();