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