錯誤寫法:
public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { lock (syncRoot) { if (instance == null) instance = new Singleton(); } return instance; } } }正確寫法:
public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } }Comment:
其實兩個寫法應該都是正確的,只是會有速度上的差別。
Reference:
https://msdn.microsoft.com/en-us/library/ff650316.aspx
沒有留言:
張貼留言