Implementing the Singleton Pattern in C# [转载]

view auther's website

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
A static variable which holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static method GetInstance as the means of accessing the instance. In all cases, the method could easily be converted to a property with only an accessor, with no impact on thread-safety or performance.

First version - not thread-safe
public sealed class Singleton
{ 
      static Singleton instance=null; 
      Singleton() 
      { 
      }
      public static Singleton GetInstance() 
      {
            if (instance==null) 
            instance = new Singleton(); 
            return instance; 
      }
 }
 

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety
public sealed class Singleton
{ 
      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      }
       public static Singleton GetInstance() 
      { 
            lock (padlock) 
            { 
                  if (instance==null) 
                  instance = new Singleton(); 
                  return instance;
             } 
      }
}
 

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking
public sealed class Singleton
{ 
      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            if (instance==null) 
            { 
                  lock (padlock) 
                  {
                        if (instance==null) 
                        instance = new Singleton(); 
                  } 
            } 
            return instance;
      }
}
 

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model is going through a reworking for version 1.5, but double-check locking is anticipated to still be broken after this.
It almost certainly doesn't work in .NET either. Claims have been made that it does, but without any convincing evidence. Various people who are rather more trustworthy, however, such as Chris Brumme, have given convincing reasons why it doesn't. Given the other disadvantages, why take the risk? I believe it can be fixed by making the instance variable volatile, but that slows the pattern down more. (Of course, correct but slow is better than incorrect but broken, but when speed was one of the reasons for using this pattern in the first place, it looks even less attractive.) It can also be fixed using explicit memory barriers, but experts seem to find it hard to agree on just which memory barriers are required. I don't know about you, but when experts disagree about whether or not something should work, I try to avoid it entirely.
It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
It still doesn't perform as well as the later implementations.
 
Fourth version - not quite as lazy, but thread-safe without using locks
public sealed class Singleton
{ 
      static readonly Singleton instance=new Singleton(); 
      // Explicit static constructor to tell C# compiler
      // not to mark type as beforefieldinit 
      static Singleton() 
      { 
      } 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            return instance; 
      }
}
 

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

It's not as lazy as the other implementations. In particular, if you have static members other than GetInstance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the method entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a method in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation
public sealed class Singleton
{ 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            return Nested.instance; 
      } 
      class Nested 
      {
            // Explicit static constructor to tell C# compiler 
            // not to mark type as beforefieldinit 
            static Nested() 
            { 
            }
             internal static readonly Singleton instance = new Singleton(); 
      }
}
 

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in GetInstance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness
In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. Conclusion
There are various different ways of implementing the singleton pattern in C#. The final two are generally best, as they are thread-safe, simple, and perform well. I would personally use the fourth implementation unless I had some other static members which really shouldn't trigger instantiation, simply because it's the simplest implementation, which means I'm more likely to get it right. The laziness of initialization can be chosen depending on the semantics of the class itself.

posted on 2004-07-18 17:21  秋枫 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zhzuo/archive/2004/07/18/25324.html

【音视频 ffmpeg 学习】 RTMP推流 mp4文件 3.当RTMP协议在互联网中传输数据的时候,消息会被拆分成更小的单元,称为消息块(Chunk)。1.RTMP(实时消息传输协议)是Adobe 公司开发的一个基于TCP的应用层协议。2.RTMP协议中基本的数据单元称为消息(Message)。下载地址:http://nginx.org/download。下载 rtmp模块 到nginx 模块下。安装nginx 和 rtmp模块。(1). linux 环境准备。下载nginx安装包。使用 vcl 播放流。 阅读详情

相关推荐

ArcGIS 10.2.2自带Python 2.7.5环境配置全攻略:从pip安装到gdal、arcpy调用

本文详细指导如何在ArcGIS 10.2.2自带的Python 2.7.5环境中进行高效配置。核心内容包括安装pip包管理器、部署gdal等关键地理数据处理库,并确保arcpy模块的无缝调用。通过解决路径配置与PyCharm集成问题,帮助用户在此经典环境中构建稳定、兼容的地理信息自动化工作流,有效连接ArcGIS桌面功能与Python脚本编程。

moon9的博客 767

8.Methods(一)

1.Instance Constructors and Classes (Reference Types) Constructors methods :   1.allow an instance of a type to be initialized to a good state.   2.are always called .ctor (for constructor) in a me...

weixin_30604651的博客 212

TB6600驱动器共阴共阳接法傻傻分不清?一张图搞定STM32与42步进电机的接线避坑指南

本文详细解析了TB6600驱动器共阴共阳接法的本质区别,提供了STM32与42步进电机的高效连接方案。通过实际案例和接线图示,帮助读者避免常见错误,确保驱动器与MCU的安全连接,提升项目稳定性。

weixin_28710999的博客 245

解决: failed to lazily initialize a collection of role: XXX, could not initialize proxy - no Session

failed to lazily initialize a collection of role: XXXXXXXX, could not initialize proxy - no Session问题解决方案

vaNaVnVan的博客 5118

Windows下Python安装geopandas全攻略:解决GDAL依赖问题的5个关键步骤

本文详细解析了在Windows系统下安装Python地理空间分析库geopandas时,如何有效解决其核心依赖GDAL的编译难题。文章提供了五个关键步骤,包括理解依赖关系、获取预编译wheel文件、顺序安装及环境验证,旨在帮助用户绕过复杂的C++编译环境,顺利完成geopandas的安装部署。

weixin_28221501的博客 285

TSP、MTSP问题遗传算法详细解读及python实现

写在前面 遗传算法是一种求解NPC问题的启发式算法,属于仿生进化算法族的一员。仿生进化算法是受生物行为启发而发明的智能优化算法,往往是人们发现某种生物的个体虽然行为较为简单,但生物集群通过某种原理却能表现出智能行为。于是不同的人研究不同的生物行为原理,受到启发而发明出新的仿生进化算法。比如免疫优化算法,蚁群算法,模拟退火算法等,这些算法以后也会简单介绍。 本文的主题是遗传算法,该算法也是受到生物行为启发。物竞天择,适者生存,优胜劣汰,是该优化算法的核心思想。笔者在业务中需要用到遗传算法求解TSP问题,但是网

weixin_47675950的博客 9306

Implementing the Singleton Pattern in C#[转载]

view authers websiteThe singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created,

5205

企业数字化转型的 4A 架构指南:从概念解读到 TOGAF 阶段对应

4A企业架构是中国数字化转型实践中总结的简化框架,包含业务、应用、数据和技术四个架构层。它自上而下形成业务驱动应用的指导关系,自下而上构建技术支撑数据的实现路径,与国际标准TOGAF核心内容高度对应。该模型通过统一语言、战略对齐和系统梳理,有效连接业务需求与IT实施,已成为企业架构规划的实用工具。其分层结构清晰展示了从业务目标到技术落地的完整推导链,特别适合中国企业的数字化转型场景。

友莘居士的博客 2175

静态构造函数线程安全的几个版本[转载]

Implementing the Singleton Pattern in C# 原文:http://www.yoda.arachsys.com/csharp/singleton.html The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singl...

weixin_30448685的博客 204

2024-江苏科技大学-模拟-动态接触角,模拟液滴撞击,comsol软件模拟。

相反,其对液滴粘度和平衡接触角的变化基本不敏感。重力势能的影响显著受过程参数调节,随着液滴直径和密度的增加而增加,而随着初始液滴速度和表面张力系数的增加而减小。通过考虑形状因子和粘度修正因子,可以准确定义表面能和粘性耗散能,使得所提出的半经验修正勺状模型表现出良好的性能,在所有65个研究案例中,液滴最大铺展长度因子(βmax)和中心厚度(h)的相对误差基本分别落在5%和10%的区间内。重力势能的影响受过程参数显著调节,随液滴直径和密度的增大而增大,随液滴初始速度和表面张力系数的增大而减小。

qq_15963745的博客 512

LVGL hal indev(porting evdev)

LVGL中对输入设备的管理是单例实现的,而在Linux的输入设备是多个的,所以需要对其进行改造成多例实现。

Bigan(安)的博客 3346

Implementing the Singleton Pattern in C#

http://www.yoda.arachsys.com/csharp/singleton.html Implementing the Singleton Pattern in C# The singleton pattern is one of the best-known patterns in software engineering. Essentially, a sing

riverlau的专栏 594

【AI智能体】飞书 AI 智能客服机器人搭建与使用实战操作详解

飞书 AI 智能客服机器人搭建与使用实战操作详解

congge 6054

贪婪逐层预训练:小数据时代的深度学习安全启动协议

贪婪逐层预训练(GLP)是一种面向深度网络冷启动的结构化初始化方法,其核心原理是通过无监督重建任务,自底向上逐层建立稳定、可解释、低敏感的特征表达基础。它不依赖海量标注数据,而是利用数据内在生成结构缓解梯度消失、特征冷启动和标签噪声三大现实困境,显著提升模型在小样本(<10k)、低算力(<16GB GPU)、高噪声场景下的收敛速度、精度稳定性与部署鲁棒性。本文聚焦GLP在现代PyTorch工程中的可复现实现,涵盖分层冻结、动态重建目标、中间表示监控等关键技术点,并延伸至Transformer、GNN与扩散模

weixin_34413103的博客 379

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

上一篇: 向RichTextBox控件不停的AppendText数据时,如何把光标的焦点始终显示到最后
下一篇: 使用FireFox的多标签浏览页功能
application0000
博客等级 码龄13年 0粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值