We had a discussion at work regarding locking and what exactly happens. The code that triggered this discussion is:
string name = (string)context.Cache[key];
if (String.IsNullOrEmpty(name)){
lock (typeof(string)){
name = (string)context.Cache[key];
//.. other code to get the name and then store in the cache
}
}
I see this as straight-forward: look for a value in the cache, if it's not there then get a lock so as nothing else interrupts whilst the code gets the name and stores it in the cache.
Our discussion focused on whether (typeof(string)) is the best way of doing things, and what exactly is does.
My question is what exactly does lock(typeof(string)) do? Does it create a local string to be used a lock or is it creating something with a wider scope and therefore potentially un-safe.
MSDN lock statement
My question is what exactly does lock(typeof(string)) do?
It locks on the Type
object referred to by the reference that the typeof
operator returns.
That means any code which does the same thing anywhere within the same process (or at least the same AppDomain) will share the same lock. Sounds like a bad idea to me.
I would suggest you create an object just for locking on:
private static readonly object CacheLock = new object();
...
lock (CacheLock)
{
...
}
That way you can easily see what's going to lock on that object.
If you lock on a Type
it will mean that you have a mutual access exclusion based on that instance of the Type
. The implications are that two threads in the application doing this will inadvertently block each other or cause unforeseen deadlocks.
Remember, typeof(someType)
just returns a Type
instance.
It is typically a best practice to dedicate an object to locking a complex process, such as declaring a readonly object
in your class. If the lock just needs to go around some access to a private variable, say a collection, then locking that collection is quite fine.
As shown on the page you link to:
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 (typeof (MyType))
is a problem ifMyType
is publicly accessible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With