以下代码摘自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指的是此方法正在操作的当前实例……但这是一个静态方法!
这有什么意义呢?
发布于 2010-05-18 23:22:55
C# lock语句不会锁定方法,而是锁定提供给它的对象。在您的例子中是syncRoot。因为这个syncRoot对象只有一个实例,所以这确保了只为该应用程序域创建一次CustomSecurityTokenServiceConfiguration类。因此,该属性可以被调用并并行执行。但是,lock { ... }中的块永远不会被并行调用。但是,它可以被多次调用,这就是额外的if (customConfiguration == null)语句在lock块中所做的事情。这种机制被称为双重检查锁。
https://stackoverflow.com/questions/2858597
复制相似问题