开发者

Singleton implementation [closed]

开发者 https://www.devze.com 2023-02-26 08:48 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I wrote a piece of code about singleton pattern implementation. Not sure its correctness. Please give some advice. Thanks.

public class Singleton
{
    public Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                if (_mutexCreation.WaitOne(0))
                {
                    try
                    {
                        if (_instance == null)
                        {
                            _instance = new Singleton();
                        }
                    }
                    finally
                    {
                        _mutexCreation.ReleaseMutex();
      开发者_StackOverflow                  _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;
}

If you do not want to use lazy loading, simply create a new instance directly in a static constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号