静态构造函数和放大器; Singleton类 [英] Static Constructor & Singleton class

查看:103
本文介绍了静态构造函数和放大器; Singleton类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现了Singleton设计模式的对象缓存。我的单身人士的做法总是懒惰负载静态实例时,第一次访问该属性。

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?

据我了解,当第一个静态属性访问时的静态构造函数将被调用。这是有效的,并且将它提供了对当前延迟加载方式的任何利益或会更好探索代理实现,或使用锁来强制它是线程安全的?

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.

干杯,
加里

推荐答案

乔恩斯基特有一个很好的文章

Jon Skeet has a nice article on singletons discussing this issue.

这篇关于静态构造函数和放大器; Singleton类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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