2016-03-25 67 views
0

比較2種方法類屬性defenition的(A & B):(C#)類的成員初始化線程安全問題

// implemention A 
public class Cache { 
    private object m_syncRoot = null; 
    public object SyncRoot { 
     get { 
      if (m_syncRoot == null) { 
       Interlocked.CompareExchange(ref m_syncRoot, new object(), null);    
      } 
      return m_syncRoot; 
     } 
    } 
} 

// implemention B. 
public class Cache { 
    public object SyncRoot { get; } = new object(); // in C# 6.0 
} 

最後一些地方使用了緩存:

static Cache MyCache = new Cache(); // I don't know if this kind of declaration is thread-safe either 
lock (MyCache.SyncRoot) { 
    .... 
} 

問題:

由於「緩存」將用作靜態實例,因此[A]中的「SyncRoot」創建爲& [B]線程安全?

回答

0

是的,這兩個創建都是線程安全的。區別在於在執行B時,SyncRoot對象在創建Cache實例時創建。並且在A中,SyncRoot在被訪問時被創建。