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

前端 未结 5 937
难免孤独
难免孤独 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 22:59

    Is there any better way for this problem?

    I use a class instead of Enum:

    public class DataCollectionManagerState
    {
        public static readonly DataCollectionManagerState Off = new DataCollectionManagerState() { };
        public static readonly DataCollectionManagerState Starting = new DataCollectionManagerState() { };
        public static readonly DataCollectionManagerState On = new DataCollectionManagerState() { };
    
        private DataCollectionManagerState() { }
    
        public override string ToString()
        {
            if (this == Off) return "Off";
            if (this == Starting) return "Starting";
            if (this == On) return "On";
    
            throw new Exception();
        }
    }
    
    public class DataCollectionManager
    {
        private static DataCollectionManagerState _state = DataCollectionManagerState.Off;
    
        public static void StartDataCollectionManager()
        {
            var originalValue = Interlocked.CompareExchange(ref _state, DataCollectionManagerState.Starting, DataCollectionManagerState.Off);
            if (originalValue != DataCollectionManagerState.Off)
            {
                throw new InvalidOperationException(string.Format("StartDataCollectionManager can be called when it's state is Off only. Current state is \"{0}\".", originalValue.ToString()));
            }
    
            // Start Data Collection Manager ...
    
            originalValue = Interlocked.CompareExchange(ref _state, DataCollectionManagerState.On, DataCollectionManagerState.Starting);
            if (originalValue != DataCollectionManagerState.Starting)
            {
                // Your code is really messy
                throw new Exception(string.Format("Unexpected error occurred. Current state is \"{0}\".", originalValue.ToString()));
            }
        }
    }
    

提交回复
热议问题