单例模式的实现

本文关键字:实现 单例模式 | 更新日期: 2023-09-27 17:50:11

我写了一段关于单例模式实现的代码。不确定它的正确性。请给一些建议。谢谢。

public class Singleton
{
    public Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                if (_mutexCreation.WaitOne(0))
                {
                    try
                    {
                        if (_instance == null)
                        {
                            _instance = new Singleton();
                        }
                    }
                    finally
                    {
                        _mutexCreation.ReleaseMutex();
                        _eventCreation.Set();
                    }
                }
                else
                {
                    _eventCreation.WaitOne();
                }
            }
            return _instance;
        }
    }
    private Singleton() { }
    private static Singleton _instance;
    private static Mutex _mutexCreation = new Mutex();
    private static ManualResetEvent _eventCreation = new ManualResetEvent(false);
}

单例模式的实现

public class Singleton
{
    private static object _syncRoot = new object();
    public Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance != null)
                       return _instance;
                    _instance = new Singleton();
                }
            }
            return _instance;
        }
    }
    private Singleton() { }
    private static Singleton _instance;
}

如果不想使用延迟加载,只需在静态构造函数中直接创建一个新实例。