假设我有一些基类
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
}
}
我的问题 - 我应该在 Interlocked.CompareExchange()之后使用哪种 HasFields 属性。存储在字段中的标志值是否是Interlocked操作后的最新值,或者我将不得不使用volatile读取?