如何实现一个单例模式 c#双重锁检查

2022-08-18 综合 108阅读

你好!以下是标准的Singleton pattern with Double-check lock。

    public class SingletonClass
    {
        private static readonly object _lock = new object();
        private static volatile SingletonClass _instance;
        public static SingletonClass Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new SingletonClass();
                        }
                    }
                }
                return _instance;
            }
        }
        private SingletonClass()
        {
            //your constructor
        }
    }

如果你的.NET在4.0以上,可以借助Lazy泛型更优雅的实现单例模式:

    public class LazySingleton
    {
        private static readonly Lazy _instance = new Lazy(() => new LazySingleton());
        private LazySingleton()
        {
            //your constructor
        }
        public static LazySingleton Instance { get { return _instance.Value; } }
    }
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com