C# 静态构造函数和单例类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1131808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:57:31  来源:igfitidea点击:

Static Constructor & Singleton class

c#multithreadingstaticsingleton

提问by GaryJL

I have an object cache which implements the Singleton design pattern. My approach to singleton was always to lazy load the static instance when the property is first accessed.

我有一个实现单例设计模式的对象缓存。我的单例方法总是在第一次访问属性时延迟加载静态实例。

public static Widget
{
    get
    {
        if(instance==null) instance = new Widget();
        return instance;
    }
}

However, I know that this approach isn't thread safe and the check for instance being null introduces a small inefficiency. Would it be wise to implement a static constructor on the class which instantiates the static instance?

但是,我知道这种方法不是线程安全的,并且检查例如为 null 会导致效率低下。在实例化静态实例的类上实现静态构造函数是否明智?

As I understand it, the static constructor would be called whenever the first static property access occurs. Is this valid, and will it provide any benefits over the current lazy load approach or would it be better to explore a proxy implementation, or use a lock to force it to be thread safe?

据我了解,只要发生第一个静态属性访问,就会调用静态构造函数。这是有效的,它会比当前的延迟加载方法提供任何好处,还是探索代理实现会更好,或者使用锁来强制它是线程安全的?

public static Widget
    {
        get
        {
            if(instance==null)
            {
                lock(padlock)
                {
                    if(instance==null) instance = new Widget();
                }
            }
            return instance;
        }
    }

I don't have a whole lot of experience with static constructors, so don't want to leap in with this idea if it is an equal or worse implementation of the lazy load property.

我对静态构造函数没有很多经验,所以如果它是延迟加载属性的同等或更差的实现,我不想跳入这个想法。

Cheers, Gary

干杯,加里

采纳答案by jason

Jon Skeet has a nice articleon singletons discussing this issue.

Jon Skeet 有一篇关于单身人士的好文章讨论了这个问题。

回答by Eric Lippert

Rather than rolling your own threadsafe lazy initializer and possibly getting it wrong, I recommend reading the msdn on Lazy<T>.

我建议您阅读 msdn 上的 msdn,而不是滚动您自己的线程安全延迟初始化程序并可能出错Lazy<T>

https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization#thread-safe-initialization

https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization#thread-safe-initialization