以下代码摘自MS用于创建新安全令牌服务网站的(Windows Identity Foundation SDK)模板。锁定(syncRoot)如何在静态方法上有意义?
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
引用了当前实例,该方法正在运行......但这是一种静态方法!
这有什么意义?
'syncRoot'定义在哪里? – Paolo 2010-05-18 15:22:58
@Paolo:这是一个很好的问题。话虽如此,我假定它是一个'static'变量或由一个Singleton返回的名称。 – Powerlord 2010-05-18 15:42:00
@Bemrose:我所做的假设是'syncRoot'是一个静态类字段,它始终保存相同的实例:'private readonly object syncRoot = new object();'。当然'syncRoot'可以定义如下:'private object syncRoot {get {return new object(); }}。在这种情况下,我们会遇到麻烦:-) – Steven 2010-05-18 15:46:45