单身实施

时间:2011-04-15 08:27:54

标签: c# .net singleton

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

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);
}

1 个答案:

答案 0 :(得分:4)

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;
}

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