lock 語句(C# 參考)

來源:互聯網
上載者:User
lock 語句(C# 參考)

lock 關鍵字將語句塊標記為臨界區,方法是擷取給定對象的互斥鎖,執行語句,然後釋放該鎖。此語句的形式如下:

Object thisLock = new Object();
lock (thisLock)
{
// Critical code section
}

有關更多資訊,請參見 線程同步(C# 編程指南)。

 備忘

lock 確保當一個線程位於代碼的臨界區時,另一個線程不進入臨界區。如果其他線程試圖進入鎖定的代碼,則它將一直等待(即被阻止),直到該對象被釋放。

線程處理(C# 編程指南) 這節討論了線程處理。

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();
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.