在Interlocked.CompareExchange()之后读取值

时间:2018-03-02 22:47:10

标签: c# .net multithreading

假设我有一些基类

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读取?

0 个答案:

没有答案