换句话说,此Singleton实现线程是否安全:
public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } }
在创建类的任何实例或访问任何静态成员之前,保证静态构造函数在每个应用程序域仅运行一次。https://docs.microsoft.com/zh- cn/dotnet/csharp/programming-guide/classes-and-structs/static- constructors
所示的实现对于初始构造是线程安全的,也就是说,构造Singleton对象不需要进行锁定或空测试。但是,这并不意味着实例的任何使用都将被同步。有很多种方法可以做到这一点。我在下面显示了一个。
public class Singleton { private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // Each call to Acquire() requires a call to Release() public static void Release() { mutex.ReleaseMutex(); } }