Lock in properties, good approach?

前端 未结 3 1823
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 11:29

In my multithreading application I am using some variables that can be altered by many instances in the same time. It is weird but it has worked fine without any problem..but of

3条回答
  •  天命终不由人
    2021-02-19 11:51

    Locking access to properties inside of accessors may lead to bogus results. For the example, look at the following code:

    class C {
        private object mylock = new object();
    
        public int A {
    
          get {
            int result;
            lock(mylock) {
            result = mA; 
            }
            return result;
          } 
    
          set { 
             lock(mylock) { 
                mA = value; 
             }
          }
        }
    }
    C obj = new C;
    C.A++;
    

    (yes, I've copied it from the first answer) There is a race condition here! Operation "C.A++" actually requires two separate accesses to A, one to get the value and the other to set the updated value. Nothing ensures that these two accesses will be carried out as together without context switch between them. Classical scenario for race condition!

    So, beware! It's not a good idea to put locks inside accessors, locks should be explicitly obtained, like the previous answer suggests (though it doesn't have to be with SyncRoots, any object will do)

提交回复
热议问题