How to easy make this counter property thread safe?

前端 未结 5 2361
陌清茗
陌清茗 2021-02-20 08:31

I have property definition in class where i have only Counters, this must be thread-safe and this isn\'t because get and set is not in same lock, How t

5条回答
  •  遇见更好的自我
    2021-02-20 09:16

    Using the Interlocked class provides for atomic operations, i.e. inherently threadsafe as in this LinqPad example:

    void Main()
    {
        var counters = new Counters();
        counters.DoneCounter += 34;
        var val = counters.DoneCounter;
        val.Dump(); // 34
    }
    
    public class Counters
    {
        int doneCounter = 0;
        public int DoneCounter
        {
            get { return Interlocked.CompareExchange(ref doneCounter, 0, 0); }
            set { Interlocked.Exchange(ref doneCounter, value); }
        }
    }
    

提交回复
热议问题