Lock in properties, good approach?

前端 未结 3 1819
被撕碎了的回忆
被撕碎了的回忆 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:59

    You need to use locks in BOTH get and set. This lock must be the same object. For example:

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

提交回复
热议问题