简体   繁体   中英

C# lock a private static object

Hi according to http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx one can declare an object for the purpose of locking:

  private Object thisLock = new Object(); 

But when I need to lock it from a static method, I need to declare it as static :

  private static Object thisLock = new Object(); 

Then more from the MSDN page,

lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.

So if it's a static object, instead of a string, will it have the problem when the same method is called multiple times, each of them tries to lock thisLock, because it's the same static object so they are actually sharing the lock?

Thank you for your time.

So if it's a static object, instead of a string, will it have the problem when the same method is called multiple times

Not exactly. Strings are special, they can be interned. You can't control their visibility like that of other objects.

The basic guidelines:

  • keep your lockObject in a close 1-on-1 relationship with the protected resource. In numbers, scope and lifetime. So use a static lockObject to protect static data.
  • keep the lockObject as private as possible, exposing it increases the risk of deadlocks. For that reason also avoid locking on Types and strings.

because it's the same static object so they are actually sharing the lock?

All code that accesses a shared resource has to share (lock on) the same lockObject instance. A private lock won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM