How to apply InterLocked.Exchange for Enum Types in C#?

前端 未结 5 926
难免孤独
难免孤独 2021-02-12 22:39
public enum MyEnum{Value1, Value2}  
class MyClass 
{ 
    private MyEnum _field;   
    public MyEnum Field  // added for convenience
    {
        get { return _field;         


        
5条回答
  •  醉话见心
    2021-02-12 23:01

    The Interlocked methods are fine. You could use a plain old lock, but that seems like overkill here. However, you are going to need to use a guarded read of some kind in the getter otherwise you may run into memory barrier issues. Since you are already using an Interlocked method in the setter it makes sense to do the same in the getter.

    public MyEnum Field  // added for convenience
    { 
      get { return (MyEnum)Interlocked.CompareExchange(ref _field, 0, 0); }
      set { Interlocked.Exchange(ref _field, (int)value); }
    }  
    

    You could also get away with marking the field as volatile if you like.

提交回复
热议问题