C#中著名的双重检查锁定技术 [英] The famous double-checked locking technique in C#

查看:37
本文介绍了C#中著名的双重检查锁定技术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一本 mprss 书中看到了这个关于单例的推荐(附上部分代码):

I saw in a mprss book this recommendation of singleton (partial code attached):

public static Singleton GetSingleton() 
{
    if (s_value != null) 
        return s_value;
    Monitor.Enter(s_lock); 
    if (s_value == null) 
    {
        Singleton temp = new Singleton();
        Interlocked.Exchange(ref s_value, temp);
    }
    Monitor.Exit(s_lock);
    return s_value;
}

<小时>

我们在第二个 if 语句块中添加了两行代码,而不是只写:


We add two lines of code in the 2nd if statement block instead of just writing:

s_value = new Singleton();

这应该处理第二个线程进入方法并找到 s_value != null 但未初始化的情况.

this should handle a situation that a second thread enters the method and finds s_value != null, but not initialized.

我的问题是,我们可以只写在第 2 个 if 块吗:

My question is, can we just write at the 2nd if block instead:

{    
    Singleton temp = new Singleton();
    s_value = temp;  // instead of Interlocked.Exchange(ref s_value, temp);    
}

那么现在的功能是:

public static Singleton GetSingleton() 
{      
    if (s_value != null)
        return s_value;

    Monitor.Enter(s_lock);   
    if (s_value == null)   
    { 
        Singleton temp = new Singleton();    
        s_value = temp; 
    }   
    Monitor.Exit(s_lock);   
    return s_value; 
} 

我想不会,因为他们不使用它.

I guess not, because they don't use it.

大家有什么建议吗?

svalue 可能包含未初始化的?svalue 可以在 temp 完全初始化后构造(我可能错了).如果我错了,你能举个例子吗?编译器会产生不同的代码吗?

It is possible that svalue may contains uninitialized? svalue can be constructed just after temp was fully initialized (may i wrong). if i wrong can u point of an example it is wrong? may the compiler produce differenent code?

推荐答案

我不会将此作为真正的答案发布,而是作为旁白发布:如果您使用 .NET 4,您真的应该考虑 Lazy

T> 单例模式:

I'll post this not as a real answer but as an aside: if you're using .NET 4 you really should consider the Lazy<T> singleton pattern:

http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx

public class LazySingleton3
{
   // static holder for instance, need to use lambda to construct since constructor private
   private static readonly Lazy<LazySingleton3> _instance
       = new Lazy<LazySingleton3>(() => new LazySingleton3());

   // private to prevent direct instantiation.
   private LazySingleton3()
   {
   }

   // accessor for instance
   public static LazySingleton3 Instance
   {
       get
       {
           return _instance.Value;
       }
   }

}

线程安全、易于阅读且显而易见:不喜欢什么?

Thread-safe, easy to read, and obvious: what's not to like?

这篇关于C#中著名的双重检查锁定技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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