静态构造函数和放大器; 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.
干杯,
加里