当前位置:主页>教程>网络编程>NET技术>Thread safe Singleton in C#

Thread safe Singleton in C#
更新时间:2007-10-17 点击:

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




tags:

您可以: 点评它!(0条点评) 分享它!

ARTHD.COM网友点评共有0条点评,点击这里可查看):不能超过250字,请自觉遵守互联网相关政策法规。

广告位



合作伙伴

广告也精彩……

广告也精彩……