简体   繁体   中英

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() . 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM