C#单例实例永远不会为空

时间:2015-04-27 18:04:42

标签: c# null singleton instance

我正在尝试在Azure webjob中实现单例模式。在本地调试实例永远不会为null。它始终设置为单例对象本身。我觉得我在这里遗漏了一些非常明显的东西。

public sealed class HubErrorList
{
    private static volatile HubErrorList instance;
    private static object syncRoot = new Object();

    private HubErrorList() {}

    public static HubErrorList Instance
    {
        get {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new HubErrorList();
                    }
                }
            }
            return instance;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

在访问该属性之前,该实例将保持为null。根据您的检查方式,您的工具可能会造成这种差异。

话虽如此,一个更简单,更好的懒惰初始化&#34;单例模式将改为使用Lazy<T>

public sealed class HubErrorList
{
    private static Lazy<HubErrorList> instance = new Lazy<HubErrorList>(() => new HubErrorList());
    private HubErrorList() {}

    public static HubErrorList Instance { get { return instance.Value; } }
}