在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么? [英] What is the best way to implement Singleton Design Pattern in C# with performance constraint?

查看:24
本文介绍了在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我知道在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么?

Please let me know what the best way to implement Singleton Design Pattern in C# with performance constraint?

推荐答案

转述自 C# in Depth:在 C# 中有多种不同的实现单例模式的方法,从对于完全延迟加载、线程安全、简单且高性能的版本而言,不是线程安全的.

Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.

最佳版本 - 使用 .NET 4 的 Lazy 类型:

Best version - using .NET 4's Lazy type:

public sealed class Singleton
{
  private static readonly Lazy<Singleton> lazy =
      new Lazy<Singleton>(() => new Singleton());

  public static Singleton Instance { get { return lazy.Value; } }

  private Singleton()
  {
  }
}

它很简单而且性能很好.它还允许您使用 IsValueCreated<检查实例是否已创建/a> 属性,如果你需要的话.

It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

这篇关于在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆