.NET 中三种正确的单例写法

it2024-08-09  57

在企业应用开发中,会出现比较多的一种情况就是,读取大对象。这种情况多适用于单例模式,单例模式在C#中有很多种写法,错误或者线程不安全的写法我就不写了。现记录常用的三种写法。

一、双重检查锁定【适用与作为缓存存在的单例模式】

public class Singleton { Singleton() { } static readonly object obj = new object(); static Singleton _instance; public static Singleton GetInstance(bool forceInit = false) { if (forceInit) { _instance = new Singleton(); } if (_instance == null) { lock (obj) { if (_instance == null) { _instance = new Singleton(); } } } return _instance; } }

二、静态内部类

public class Singleton { Singleton() { } private static class SingletonInstance { public static Singleton Instance = new Singleton(); } public static Singleton Instance => SingletonInstance.Instance; }

三、使用System.Lazy<T>延迟加载 【推荐】

Lazy 对象初始化默认是线程安全的,在多线程环境下,第一个访问 Lazy 对象的 Value 属性的线程将初始化 Lazy 对象,以后访问的线程都将使用第一次初始化的数据。

//单纯的单例模式 public sealed class Singleton { Singleton() { } static readonly Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton()); public static Singleton GetInstance => lazySingleton.Value; } //更新缓存的单例模式 public sealed class Singleton { Singleton() { } static Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton()); public static Singleton GetInstance(bool forceInit = false) { if (forceInit) { lazySingleton = new Lazy<Singleton>(() => new Singleton()); } return lazySingleton.Value; } }

转载于:https://www.cnblogs.com/xuxuzhaozhao/p/10248483.html

最新回复(0)