Reputation: 867
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.
Upvotes: 1
Views: 2237
Reputation: 273244
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:
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.
Upvotes: 4