C#单例测试(懒汉式双锁保证线程安全)
单例模式的概念
单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
关键点:
- 这个类只有一个实例,这是最基本的
- 它必须自行创建这个实例,外部不能实例化
- 进程内唯一
代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WCF_Host_Service { /// <summary> /// 服务程序唯一上下文对象(单例) /// </summary> public sealed class ServiceContext { private static ServiceContext _ServiceContext = null; private readonly static object lockObj = new object(); /// <summary> /// 禁止外部进行实例化 /// </summary> private ServiceContext() { } /// <summary> /// 获取唯一实例,双锁定防止多线程并发时重复创建实例 /// </summary> /// <returns></returns> public static ServiceContext GetInstance() { if (_ServiceContext == null) { lock (lockObj) { if (_ServiceContext == null) { _ServiceContext = new ServiceContext(); } } } return _ServiceContext; } } }
关键点: 1)私有的构造函数 2)两次进行唯一实例的内部成员变量是否为空的判断。第二次判断时是在lock的前提下进行的。所以是唯一的,这次判断保证了是否为空的结论是线程安全的。
测试过程
ConcurrentDictionary<int, ServiceContext> dict = new ConcurrentDictionary<int, ServiceContext>(); Action testTask = () => { ServiceContext sc = ServiceContext.GetInstance(); if (sc != null && !dict.ContainsKey(sc.GetHashCode())) { dict.TryAdd(sc.GetHashCode(), sc); } Thread.Sleep(1); }; int index = 0; while (index < 1024) { Parallel.Invoke(testTask,testTask); index++; } Debugger.Log(0,"",string.Format("测试共生出{0}个实例。",dict.Count));
利用反射外部强制实例化测试:
var type = this.GetType().Assembly.GetType(typeof(ServiceContext).FullName); var sc = Activator.CreateInstance(type);
作者:数据酷软件
出处:https://www.cnblogs.com/datacool/p/datacool_2017_notedl.html
关于作者:20年编程从业经验,持续关注MES/ERP/POS/WMS/工业自动化
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。
联系方式: qq:71008973;wx:6857740733
基于人脸识别的考勤系统 地址: https://gitee.com/afeng124/viewface_attendance_ext
自己开发安卓应用框架 地址: https://gitee.com/afeng124/android-app-frame
WPOS(warehouse+pos) 后台演示地址: http://47.239.106.75:8080/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构