lock(syncRoot)如何在静态方法上有意义?

时间:2010-05-18 15:18:17

标签: c# multithreading synclock

以下代码摘自MS用于创建新安全令牌服务网站的(Windows Identity Foundation SDK)模板。

public static CustomSecurityTokenServiceConfiguration Current  
{  
    get  
    {
        var key = CustomSecurityTokenServiceConfigurationKey;

        var httpAppState = HttpContext.Current.Application;

        var customConfiguration = httpAppState.Get(key)
            as CustomSecurityTokenServiceConfiguration;  

        if (customConfiguration == null)
        {  
            lock (syncRoot)
            {
                customConfiguration = httpAppState.Get(key)
                    as CustomSecurityTokenServiceConfiguration;  

                if (customConfiguration == null)
                {
                    customConfiguration =
                        new CustomSecurityTokenServiceConfiguration();  
                    httpAppState.Add(key, customConfiguration);
                }
            }
        }    
        return customConfiguration;  
    }
}

我对多线程编程比较陌生。我假设lock语句的原因是,如果两个Web请求同时到达Web站点,则此代码是线程安全的。

但是,我原以为使用lock (syncRoot)没有意义,因为syncRoot引用了此方法正在运行的当前实例......但这是一个静态方法!

这有什么意义?

1 个答案:

答案 0 :(得分:6)

C#lock语句不会锁定方法,而是锁定它所提供的对象。在您的情况下syncRoot。由于此syncRoot对象只有一个实例,因此可确保只为该应用程序域创建一次CustomSecurityTokenServiceConfiguration类。因此可以调用属性并并行执行。但是,lock { ... }中的块永远不会被并行调用。但是,它可以被多次调用,这就是额外的if (customConfiguration == null)语句在lock块中所做的事情。这种机制称为双重检查锁。

相关问题