簡體   English   中英

在C#中對應用程序進行線程化時鎖定類和屬性的正確方法

[英]Proper method for Locking Classes and Properties when threading applications in C#

我要求編碼約定以及在類中的屬性和方法上使用鎖定機制的正確方法。

例如,我有兩個屬性和兩個方法:

public class FOO
{
private Guid uniqueIdentifier;
object _syncuniqueIdentifier = new object();
public Guid UniqueIdentifier 
{
       get 
       { 
        lock(_syncuniqueIdentifier)
        {
        return uniqueIdentifier;
        }        
    }
    set 
    { 
         lock(_syncuniqueIdentifier)
         {  
        uniqueIdentifier = value;
         }          
    }
}

private string userName;
object _syncuserName = new object();
public string UserName 
{
       get 
       { 
        lock(_syncuserName)
        {
        return userName;
        }        
    }
    set 
    { 
         lock(_syncuserName)
         {  
        userName = value;
         }          
    }
}

object _syncMyMethod = new object();
public void myMethod(object argument1, object argument2)
{
   lock(_syncMyMethod)
   {
   do work with argument1 and argument2
   }
}


}

我是在使用正確的模式來實現線程,還是應該將單個對象_syncLock並在該對象上鎖定所有屬性和方法? 這樣做的編碼標准是什么?

是的,您正在使用有效模式,假設字段是獨立的且經常更改。 只要在鎖下沒有太多計算,使用單個鎖對象也是合理的選擇。

如果兩個(或多個)字段是從屬字段,則在屬性級別上的鎖定將不起作用(即使使用單個對象進行鎖定),您也應在屬性外部進行鎖定,或者重組API以防止僅修改一個屬性。

呼叫者要注意鎖定:

// no locks here, all callers to lock
public class FOO {
   public Guid UniqueIdentifier {get;set;}
   public string UserName {get;set;}
}

// in caller code
usersLock = new object();
List<FOO> users = ...

lock(usersLock) 
{
    // modify/read users here.
    ...
}

替代API:

public class FOO {
  private object idLock = new Object();

  // immutable Id class
  public class Id {
   public Id(....){...}
   public Guid UniqueIdentifier {get; private set;}
   public string UserName {get; private set;}
  }

  private Id id;
  public Id { get {lock(idLock){ return id;}}
              set {lock(idLock){ id = value;}}
}

請注意,基於示例中的字段名稱( UniqueIdentifierUserName ),這些字段會合並在一起,並且在字段級別上鎖定只會在“無例外”的意義上提供線程安全,但是讓兩個彼此不同步很簡單-因此,可能需要改用上述方法之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM