您的位置:首页 > Web前端

Thread safe Singleton in C#

2005-06-15 16:27 375 查看
    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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息