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

Dan*_*don 3 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;  
    }
}
Run Code Online (Sandbox Code Playgroud)

我对多线程编程比较陌生.我假设声明的原因lock是在两个Web请求同时到达Web站点的情况下使此代码成为线程安全的.

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

这有什么意义?

Ste*_*ven 6

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