R# - 双重检查锁定模式可能不正确的实现
R# - Possible incorrect implementation of Double-Check Locking pattern
private readonly Object _syncRoot = new Object();
public IdGenerator ClientIdGenerator
{
get
{
if ( clientIdGenerator != null )
return clientIdGenerator;
lock ( _syncRoot )
{
if ( clientIdGenerator != null )
return clientIdGenerator;
return clientIdGenerator = ClientIdPrefix != null ? new IdGenerator( ClientIdPrefix ) : new IdGenerator();
}
}
}
R# 在创建 IdGenerator 实例的行上显示警告 "Possible incorrect implementation of Double-Check Locking pattern. Read access to checked field"。
我将代码更改为以下内容后,R# 不显示警告:
public IdGenerator ClientIdGenerator
{
get
{
if ( clientIdGenerator == null )
lock ( _syncRoot )
{
if ( clientIdGenerator != null )
return clientIdGenerator;
clientIdGenerator = ClientIdPrefix != null ? new IdGenerator( ClientIdPrefix ) : new IdGenerator();
}
return clientIdGenerator;
}
}
第一个示例有什么问题吗,或者 R# 是否显示 "wrong" 警告?
你的第一个版本应该可以很好地工作,但为了避免部分代码分析引擎或同事的误解,你可以使用标准模式:
private readonly Object _syncRoot = new Object();
public IdGenerator ClientIdGenerator
{
get
{
if (clientIdGenerator == null)
{
lock (_syncRoot)
{
if (clientIdGenerator == null)
{
clientIdGenerator = ClientIdPrefix != null ? new IdGenerator(ClientIdPrefix) : new IdGenerator();
}
}
}
return clientIdGenerator;
}
}
这样你就可以明确你的意图。
private readonly Object _syncRoot = new Object();
public IdGenerator ClientIdGenerator
{
get
{
if ( clientIdGenerator != null )
return clientIdGenerator;
lock ( _syncRoot )
{
if ( clientIdGenerator != null )
return clientIdGenerator;
return clientIdGenerator = ClientIdPrefix != null ? new IdGenerator( ClientIdPrefix ) : new IdGenerator();
}
}
}
R# 在创建 IdGenerator 实例的行上显示警告 "Possible incorrect implementation of Double-Check Locking pattern. Read access to checked field"。
我将代码更改为以下内容后,R# 不显示警告:
public IdGenerator ClientIdGenerator
{
get
{
if ( clientIdGenerator == null )
lock ( _syncRoot )
{
if ( clientIdGenerator != null )
return clientIdGenerator;
clientIdGenerator = ClientIdPrefix != null ? new IdGenerator( ClientIdPrefix ) : new IdGenerator();
}
return clientIdGenerator;
}
}
第一个示例有什么问题吗,或者 R# 是否显示 "wrong" 警告?
你的第一个版本应该可以很好地工作,但为了避免部分代码分析引擎或同事的误解,你可以使用标准模式:
private readonly Object _syncRoot = new Object();
public IdGenerator ClientIdGenerator
{
get
{
if (clientIdGenerator == null)
{
lock (_syncRoot)
{
if (clientIdGenerator == null)
{
clientIdGenerator = ClientIdPrefix != null ? new IdGenerator(ClientIdPrefix) : new IdGenerator();
}
}
}
return clientIdGenerator;
}
}
这样你就可以明确你的意图。