[英]Reading value after Interlocked.CompareExchange()
Suppose I have some base class假设我有一些基类
public abstract class ReflectionSupport
{
private const int UnresolvedFieldsFlag = -1;
private const int TrueFieldsFlag = 1;
private const int FalseFieldsFlag = 0;
// flag holder
private int _flagHasFields = UnresolvedFieldsFlag;
// variant 1
protected bool HasFields
{
get
{
Interlocked.CompareExchange(ref _flagHasFields, ResolveHasFieldsFlag(), UnresolvedFieldsFlag);
return (TrueFieldsFlag == Volatile.Read(ref _flagHasFields));
}
}
// variant 2
protected bool HasFields
{
get
{
Interlocked.CompareExchange(ref _flagHasFields, ResolveHasFieldsFlag(), UnresolvedFieldsFlag);
return (TrueFieldsFlag == _flagHasFields);
}
}
private int ResolveHasFieldsFlag()
{
// here reflection is used
// to analyze current instance
// and returns TRUE-flag if instance
// contains field
}
}
My question - what variant HasFields property I should use after Interlocked.CompareExchange() .我的问题 - 在Interlocked.CompareExchange()之后我应该使用什么变体HasFields属性。 Is the value of flag stored in field is the latest one after Interlocked operation or I will have to use volatile read?存储在字段中的标志值是联锁操作后的最新值还是我将不得不使用易失性读取?
Based on the info of your comment, you can just use Lazy
in the following way根据您的评论信息,您可以通过以下方式使用Lazy
public abstract class ReflectionSupport
{
private readonly Lazy<bool> _hasFields;
protected bool HasFields => _hasFields.Value;
protected ReflectionSupport()
{
_hasFields = new Lazy<bool>(HasFieldsFlag);
}
private bool HasFieldsFlag()
{
// just return true if instance
// contains field
}
}
As you can see there is no more need in UnresolvedFieldsFlag
, so bool
can be used instead如您所见,不再需要UnresolvedFieldsFlag
,因此可以使用bool
代替
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.