几种常用的C#线程安全的单例方式

整理了几种常用的C#线程安全的单例方式

复制代码
namespace SafeSingleton
{
    /// <summary>
    /// 线程安全的单例方式:CAS
    /// </summary>
    class Singleton_CAS
    {
        private static Singleton_CAS single;
        public static Singleton_CAS Singleton()
        {
            if (single != null) return single;
            System.Threading.Interlocked.CompareExchange(ref single, new Singleton_CAS(), null);
            return single;
        }
    }
    /// <summary>
    /// 线程安全的单例方式:Lazy加载
    /// </summary>
    class Singleton_Lazy
    {
        public static Singleton_Lazy Singleton() { return single.Value; }
        private static readonly System.Lazy<Singleton_Lazy> single = new System.Lazy<Singleton_Lazy>(() => new Singleton_Lazy());
    }
    /// <summary>
    /// 线程安全的单例方式:静态内部类-懒汉/饿汉模式
    /// </summary>
    class Singleton_StaticClass
    {
        //public static Singleton_StaticClass Singleton => InnerClass.single;//饿汉模式
        public static Singleton_StaticClass Singleton() { return InnerClass.single; }//懒汉模式
        private static class InnerClass
        {
            internal static Singleton_StaticClass single = new Singleton_StaticClass();
        }
    }
    /// <summary>
    /// 线程安全的单例方式:双重校验-懒汉模式
    /// </summary>
    class Singleton_DoubleCheck
    {
        private static readonly object lockObj = new object();
        private static Singleton_DoubleCheck single;
        public static Singleton_DoubleCheck Singleton()
        {
            if (single == null)
            {
                //System.Threading.Monitor.Enter(lockObj);
                lock (lockObj)
                {
                    if (single == null)
                    {
                        single = new Singleton_DoubleCheck();
                    }
                }
          //System.Threading.Monitor.Exit(lockObj); }
return single; } } /// <summary> /// 线程安全的单例方式:静态只读字段-饿汉模式 /// </summary> class Singleton_StaticReadonlyField { private static readonly Singleton_StaticReadonlyField single = new Singleton_StaticReadonlyField(); public static Singleton_StaticReadonlyField Singleton() { return single; } } }
复制代码

 

posted on   鱼歌  阅读(174)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示