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]線程安全?