C#中實現線程同步lock關鍵字的用法詳解_C#教程

來源:互聯網
上載者:User

1. lock關鍵字保證一個代碼塊在執行的過程中不會受到其他線程的幹擾,這是通過在該代碼塊的運行過程中對特定的對象加互斥鎖來實現的。

2. lock關鍵字的參數必須是參考型別的對象。lock對基礎資料型別 (Elementary Data Type)如int,long等無效,因為它所作用的類型必須是對象。如果傳入long類型資料,勢必被轉換為Int64結構類型,則加鎖的是全新的對象引用。如果需要對它們進行互斥訪問限制,可以使用System.Threading.Interlocked類提供的方法,這個類是提供原子操作的。

3. lock(this)的使用要謹慎。共有類型中使用lock(this),如果新的對象被建立並加鎖,極易造成死結。

4. 鎖定ICollection類型對象時,應lock其SyncRoot屬性。

SyncRoot屬性在介面ICollection中聲明,其實現方式各不相同。

例如在Collection(System.Collections.ObjectModel)中實現如下:

object ICollection.SyncRoot {      get      {           if (this._syncRoot == null)           {                ICollection items = this.items as ICollection;                if (items != null)                {                     this._syncRoot = items.SyncRoot;                }                else                {                     Interlocked.CompareExchange(ref this._syncRoot, new object(), null);                }           }           return this._syncRoot;      } } 

而在List<T>,ArrayList等類中實現如下:

object ICollection.SyncRoot {      get      {           if (this._syncRoot == null)           {                Interlocked.CompareExchange(ref this._syncRoot, new object(), null);           }           return this._syncRoot;      } }   

在Array類中則直接返回了this:

public object SyncRoot {      get      {           return this;      } } 

5. lock關鍵字是用Monitor(管程)類實現的

lock(x) {   DoSomething(); } 
System.Object obj = (System.Object)x; System.Threading.Monitor.Enter(obj); try {   DoSomething(); } finally {   System.Threading.Monitor.Exit(obj); } 

以上兩段代碼是等效的。(MSDN)

使用lock關鍵字相對於Monitor類在使用上更簡單,也更加保險。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.