以下代码摘自 MS 用于创建新的安全 token 服务网站的 (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 请求同时到达网站的情况下使此代码线程安全。
但是,我本来认为使用lock (syncRoot)
没有任何意义,因为syncRoot
指的是该方法正在运行的当前实例……但是这是一个静态方法!
这有什么意义?
最佳答案
C# lock
语句不锁定方法,而是锁定提供给它的对象。在你的情况下 syncRoot
。因为此 syncRoot
对象只有一个实例,所以这确保了 CustomSecurityTokenServiceConfiguration
类只会为该应用域创建一次。因此可以并行调用和执行该属性。但是,lock { ... }
中的 block 永远不会被并行调用。但是,它可以被多次调用,这就是额外的 if (customConfiguration == null)
语句在 lock
block 中所做的事情。这种机制称为双重检查锁。
关于c# - lock(syncRoot) 对静态方法有何意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2858597/