开发者

why should we avoid lock(this)? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why is lock(this开发者_StackOverflow) {…} bad?

In C# to make a critical region thread safe we can use lock() statement. The lock statement takes an object. What is wrong if we pass this to the lock statement?


Because this is not encapsulated by the class and thus it is hard to reason about who locks on this. I.e. in order to find out what part of the code is locking on this you need to go through a lot. If, on the other hand, you restrict locking to a private member, it is easy to reason about where locking takes place.


From http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx:

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜