線程是經過擴展 Thread 類建立的。擴展的 Thread 類調用 Start() 方法來開始子線程的執行。編輯器
下面的程序演示了這個概念:spa
class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } }
當上面的代碼被編譯和執行時,它會產生下列結果:線程
In Main: Creating the Child thread
Child thread starts
Thread 類提供了各類管理線程的方法。code
下面的實例演示了 sleep() 方法的使用,用於在一個特定的時間暫停線程。blog
class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); // 線程暫停 5000 毫秒 int sleepfor = 5000; Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000); Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } }
當上面的代碼被編譯和執行時,它會產生下列結果:string
In Main: Creating the Child thread Child thread starts Child Thread Paused for 5 seconds Child thread resumes
Abort() 方法用於銷燬線程。it
經過拋出 threadabortexception 在運行時停止線程。這個異常不能被捕獲,若是有 finally 塊,控制會被送至 finally 塊。io
下面的程序說明了這點:編譯
class ThreadCreationProgram { public static void CallToChildThread() { try { Console.WriteLine("Child thread starts"); // 計數到 10 for (int counter = 0; counter <= 10; counter++) { Thread.Sleep(500); Console.WriteLine(counter); } Console.WriteLine("Child Thread Completed"); } catch (ThreadAbortException e) { Console.WriteLine("Thread Abort Exception"); } finally { Console.WriteLine("Couldn't catch the Thread Exception"); } } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); // 中止主線程一段時間 Thread.Sleep(2000); // 如今停止子線程 Console.WriteLine("In Main: Aborting the Child thread"); childThread.Abort(); Console.ReadKey(); } }
當上面的代碼被編譯和執行時,它會產生下列結果:class
In Main: Creating the Child thread Child thread starts 0 1 2 In Main: Aborting the Child thread Thread Abort Exception Couldn't catch the Thread Exception