单例线程安全

一些帮助类或者其他的工具类经常会用到单例,这里总结一下单例线程安全比较好的两种方式1,Lazy,2,Lock这种写法比较简单常见,但是会影响高并发的性能

    public class Helper
    {
        private static object obj = new object();
        public Helper()
        {
            Console.WriteLine("构造方法");
        }
        private static Lazy<Helper> LInstance = new Lazy<Helper>(() => { return new Helper(); });
        public string Name;
        public static Helper Instance
        {
            get
            {
                return LInstance.Value;
            }
        }
        public static bool IsValueCreated
        {
            get
            {
                return LInstance.IsValueCreated;
            }
        }
        private static Helper nonInstance;
        public static Helper NonInstance
        {
            get
            {
                lock (obj)
                {
                    if (nonInstance == null)
                        nonInstance = new Helper();
                    return nonInstance;
                }
            }
        }
    }

 

//下面是我的测试 

 

class Program

 

    {
        static void Main(string[] args)
        {
            //lazy
            //Task.Run(() => { TestLazyInstance(); });
            //Task.Run(() => { TestLazyInstance(); });
            //Task.Run(() => { TestLazyInstance(); });
            //Task.Run(() => { TestLazyInstance(); });
            //普通单例,加上lock才能保证线程安全
            Task.Run(() => { TestNorMalInstance(); });
            Task.Run(() => { TestNorMalInstance(); });
            Task.Run(() => { TestNorMalInstance(); });
            Task.Run(() => { TestNorMalInstance(); });
            Console.ReadKey();
        }
        private static void TestLazyInstance()
        {
            if (!Helper.IsValueCreated)
                Console.WriteLine("还没有实例化");
            Helper.Instance.Name = "haha";
            Console.WriteLine(Helper.Instance.Name);
        }
        private static void TestNorMalInstance()
        {
            //if (!Helper.IsValueCreated)
            //    Console.WriteLine("还没有实例化");
            Helper.NonInstance.Name = "haha";
            Console.WriteLine(Helper.NonInstance.Name);
        }
    }

 

posted @ 2017-08-25 14:41  华强国邦  阅读(194)  评论(0编辑  收藏  举报