c#语法之lock 语句
lock 關鍵字將語句塊標記為臨界區,方法是獲取給定對象的互斥鎖,執行語句,然后釋放該鎖。此語句的形式如下:
Object thisLock = new Object(); lock (thisLock) { // Critical code section. }lock 關鍵字可確保當一個線程位于代碼的臨界區時,另一個線程不會進入該臨界區。如果其他線程試圖進入鎖定的代碼,則它將一直等待(即被阻止),直到該對象被釋放。
lock 關鍵字在塊的開始處調用 Enter,而在塊的結尾處調用 Exit。
通常,應避免鎖定 public 類型,否則實例將超出代碼的控制范圍。常見的結構 lock (this)、lock (typeof (MyType)) 和 lock ("myLock") 違反此準則:
-
如果實例可以被公共訪問,將出現 lock (this) 問題。
-
如果 MyType 可以被公共訪問,將出現 lock (typeof (MyType)) 問題。
-
由于進程中使用同一字符串的任何其他代碼都將共享同一個鎖,所以出現 lock(“myLock”) 問題。
最佳做法是定義 private 對象來鎖定, 或 private static 對象變量來保護所有實例所共有的數據。
下例顯示的是在 C# 中使用線程的簡單示例。
// statements_lock.cs using System; using System.Threading; ? class ThreadTest { public void RunMe() { Console.WriteLine("RunMe called"); } ? static void Main() { ThreadTest b = new ThreadTest(); Thread t = new Thread(b.RunMe); t.Start(); } }結果為:
RunMe called?
下例使用線程和 lock。只要 lock 語句存在,語句塊就是臨界區并且 balance 永遠不會是負數。
// statements_lock2.cs using System; using System.Threading; ? class Account { private Object thisLock = new Object(); int balance; ? Random r = new Random(); ? public Account(int initial) { balance = initial; } ? int Withdraw(int amount) { ? // This condition will never be true unless the lock statement // is commented out: if (balance < 0) { throw new Exception("Negative Balance"); } ? // Comment out the next line to see the effect of leaving out // the lock keyword: lock(thisLock) { if (balance >= amount) { Console.WriteLine("Balance before Withdrawal : " + balance); Console.WriteLine("Amount to Withdraw : -" + amount); balance = balance - amount; Console.WriteLine("Balance after Withdrawal : " + balance); return amount; } else { return 0; // transaction rejected } } } ? public void DoTransactions() { for (int i = 0; i < 100; i++) { Withdraw(r.Next(1, 100)); } } } ? class Test { static void Main() { Thread[] threads = new Thread[10]; Account acc = new Account(1000); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(acc.DoTransactions)); threads[i] = t; } for (int i = 0; i < 10; i++) { threads[i].Start(); } } }轉載于:https://www.cnblogs.com/superfang/archive/2008/06/29/1232164.html
總結
以上是生活随笔為你收集整理的c#语法之lock 语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CrystalDecisions.Cry
- 下一篇: Demo:充分利用 Ajax 技术 来体