Thread safe Singleton in C#

来源:互联网 发布:专业编曲软件 编辑:程序博客网 时间:2024/05/22 10:33

    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