lock(syncRoot) 对静态方法有何意义?
以下代码摘自 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 请求同时到达网站的情况下使该代码线程安全。
但是,我认为使用 lock (syncRoot)
没有意义,因为 syncRoot
引用此方法正在操作的当前实例...但这是一个静态方法!
这有什么意义呢?
The following code is excerpted from the (Windows Identity Foundation SDK) template that MS uses to create a new Security Token Service Web Site.
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;
}
}
I'm relatively new to multi-threaded programming. I assume that the reason for the lock
statement is to make this code thread-safe in the event that two web requests arrive at the web site at the same time.
However, I would have thought that using lock (syncRoot)
would not make sense because syncRoot
refers to the current instance that this method is operating on... but this is a static method!
How does this make sense?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C#
lock
语句不会锁定方法,而是锁定提供给它的对象。在您的情况下syncRoot
。由于此syncRoot
对象只有一个实例,因此这可确保仅为该应用程序域创建一次CustomSecurityTokenServiceConfiguration
类。因此该属性可以并行调用并执行。但是,lock { ... }
中的块永远不会被并行调用。但是,它可以被多次调用,这就是额外的if (customConfiguration == null)
语句在lock
块中执行的操作。这种机制称为双重检查锁。The C#
lock
statement does not lock on a method, but on the object it is supplied to. In your casesyncRoot
. Because there is only one instance of thissyncRoot
object, this ensures theCustomSecurityTokenServiceConfiguration
class will only get created once for that app domain. So the property can be called in and executed in parallel. However, the block within thelock { ... }
will never be called in parallel. However, it can be called multiple times and that is what the extraif (customConfiguration == null)
statement is doing within thelock
block. This mechanism is called a double checked lock.