能夠認爲線程是一個虛擬進程,用於獨立運行一個特定的程序。c#
1.使用c#建立線程函數
using System; using System.Threading; //3 namespace MutiThreadDemo { class Program { static void Main(string[] args) {
//5 Thread t = new Thread(PrintNumber); t.Start(); PrintNumber(); Console.ReadLine(); } //4 static void PrintNumber() { Console.WriteLine("Starting ..."); for(int i = 1;i< 10; i++) { Console.WriteLine(i); } } } }
在上面的代碼中,步驟4定義了方法 PrintNumber , 該方法會被主線程和新建立的線程使用。spa
在咱們構造一個線程時,ThreadStart 或 ParameterizedThreadStart 的實例委託會傳給構造函數。操作系統
咱們只需指定在不一樣線程運行的方法名,而 c# 編譯器則會在後臺建立這些對象。線程
運行結果:兩組範圍爲1 -10的數字會隨機交叉輸出。這說明了PringNumber方法同時運行在主線程和另外一個線程。(若是10個數字隨機交叉不明顯,能夠增長到100試試)code
2.暫停線程對象
這裏展現如何讓一個線程等待一段時間而不用消耗操做系統資源。blog
using System; using System.Threading; namespace MutiThreadDemo { class ThreadSleep { static void Main(string[] args) { Thread t = new Thread(PrintNumbersWithDelay); t.Start(); PrintNumbers(); Console.ReadLine(); } static void PrintNumbers() { Console.WriteLine("Starting ..."); for (int i = 0; i < 10; i++) { Console.WriteLine(i); } } static void PrintNumbersWithDelay() { Console.WriteLine("Starting ..."); for(int i = 0; i < 10; i++) { Thread.Sleep(TimeSpan.FromSeconds(2)); Console.WriteLine(i); } } } }
在PrintNumbersWithDeplay方法中加入了Thread.Sleep方法調用。這會致使線程在執行該代碼時,在打印任何數字以前會等待指定的時間(這裏是2秒鐘)。進程
3.線程等待資源
這裏將展現如何讓程序等待另外一個程序中的計算完成,而後在代碼中使用該線程的計算結果。
使用Thread.Sleep行不通,由於並不知道計算須要花費的具體時間。
using System; using System.Threading; namespace MutiThreadDemo { class Thread_Join { static void Main(string[] args) { Console.WriteLine("Starting ..."); Thread t = new Thread(PrintNumbersWithDeplay); t.Start(); t.Join(); Console.WriteLine("Thread completed"); Console.ReadLine(); } static void PrintNumbersWithDeplay() { Console.WriteLine("Starting ..."); for (int i = 1; i < 10; i++) { Thread.Sleep(TimeSpan.FromSeconds(2)); Console.WriteLine(i); } } } }
運行結果:
當程序運行時,啓動了一個耗時較長的線程來打印數字,打印每一個數字前要等待兩秒。
可是咱們在主程序中調用了 t.Join 方法,該方法容許咱們等待直到線程 t 完成。
當線程 t 完成時,主程序會繼續運行。
藉助該技術能夠實如今兩個線程間同步執行步驟。
4.終止線程
...