C# \ Lock \ lock instance member VS lock static member

天大地大妈咪最大 提交于 2019-12-11 06:24:37

问题


what is better? is there any difference in runtime between the two options?


回答1:


There is no runtime difference between locking a static and locking an instance member. However, it can break your code if you use an instance lock and are updating a static.

class Broken {
  static int myCounter;
  object synch = new object();

  void SomeMethod()
  {
      lock (synch) { // BAD
        ++myCounter; 
      }
  }
}



回答2:


Huh? I thought it should depend on what you are locking for. If you are trying to lock a non-static object, it should be locking non-static object. By the way, you might want to investigate on what you are trying to do, most of the time, there are already thread safe objects built-in language.




回答3:


Why are you locking a non-static method ? You typically only need synchronization around access to a shared resource, i.e. one that will be shared among all threads. You wouldn't do this with an instance method, you'd want a singleton.



来源:https://stackoverflow.com/questions/6567567/c-sharp-lock-lock-instance-member-vs-lock-static-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!