Thread safe Singleton in C#

博客展示了一个用C#实现的单例模式代码。通过定义私有构造函数、静态变量和锁机制,确保在多线程环境下单例对象的创建是线程安全的,避免了重复创建单例对象的问题。

    public sealed class Singleton

    {

        private Singleton() {}

        private static volatile Singleton _value;

        private static object syncRoot = new Object();

        public static Singleton Value

        {

            get

            {

                if (_value == null)

                {

                    lock (syncRoot)

                    {

                        if (_value == null)

                        {

                            _value = new Singleton();

                        } //end inner if

                    } //end lock

                } //end outer if

                return _value;

            } //end get

        } //end Value

    } //end class

        Double-check locking is used to ensure that exactly one instance is ever created and only when needed

       syncRoot is used to lock on rather than locking on the type itself to avoid deadlocks caused by outside code

        The _value instance is declared to be volatile in order to assure that the assignment to _value and any writes inside the Singleton constructor complete before the instance can be accessed

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值