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.
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.
See more on this question at Stackoverflow