C#構建多執行緒應用程式(4) —— 併發問題
阿新 • • 發佈:2019-02-05
在構建多執行緒的應用程式時,我們需要找到一種方式來控制多個執行緒對共享資源的同步訪問。System.Threading名稱空間提供了一些以同步為中心的型別。C#程式語言也提供了一個特別的關鍵字,它能在多執行緒程式中同步共享資料。
使用C#的lock關鍵字實現執行緒同步
同步訪問共享資源的首選技術是C#的lock關鍵字。這個關鍵字允許定義一段執行緒同步的程式碼語句。Lock關鍵字需要定義一個標記,即一個物件引用,執行緒在進入鎖定範圍的時候必須獲得這個標記。
如果需要鎖定安全成員中的一段程式碼,比較安全的方式是宣告私有的object成員來作為鎖標記。一旦一個執行緒進入鎖定範圍,在它退出鎖定範圍且釋放鎖定之前,其他執行緒將無法訪問鎖定標記。因此,如果執行緒 A獲得鎖定標記,直到它放棄這個鎖定標記,其他執行緒才能進入鎖定範圍。
下面顯示了使用lock關鍵字來實現執行緒同步的示例程式碼:
<span style="font-size:14px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MultiThread { class Program { public static object threadLock = new object(); public static int number = 1; public static void Printer() { lock (threadLock) { for (int i = 1; i < 11; i++) { if (i % 10 != 0) { Console.WriteLine("thread {0} output the number:{1}.", Thread.CurrentThread.ManagedThreadId, number++); } } } } static void Main(string[] args) { //建立執行緒 Thread SleepThread1 = new Thread(new ThreadStart(Printer)); Thread SleepThread2 = new Thread(new ThreadStart(Printer)); //啟動執行緒 SleepThread1.Start(); SleepThread2.Start(); Console.WriteLine("the sleep thread is over!"); Console.ReadLine(); } } }</span>
執行結果如下:
使用System.Threading.Monitor型別進行同步
大多數情況下,使用lock關鍵字就夠用了,但System.Threading.Monitor型別比lock關鍵字有更好的控制力。
public static void Printer() { Monitor.Enter(threadLock); for (int i = 1; i < 11; i++) { if (i % 10 != 0) { Console.WriteLine("thread {0} output the number:{1}.", Thread.CurrentThread.ManagedThreadId, number++); } } Monitor.Exit(threadLock); }
使用Monitor型別還可以使用Monitor.Wait()方法指示活動的執行緒等待一段時間,在當前執行緒完成操作時,通知等待執行緒。