Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using lock(typeof(string))

Tags:

c#

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

like image 625
Daniel Hollinrake Avatar asked Oct 30 '13 15:10

Daniel Hollinrake


3 Answers

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.

like image 135
Jon Skeet Avatar answered Oct 23 '22 18:10

Jon Skeet


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.

like image 40
Michael J. Gray Avatar answered Oct 23 '22 18:10

Michael J. Gray


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 if MyType is publicly accessible.

like image 37
CodeCaster Avatar answered Oct 23 '22 17:10

CodeCaster