views:

632

answers:

6

MSDN gives the following warning about the lock keyword in C#:

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 (this) is a problem if the instance can be accessed publicly.
* lock (typeof (MyType)) is a problem if MyType is publicly accessible.

Yet it gives no solid reasoning for it. The lock(this) is explained here on SO. I'm interested in lock(typeof(MyType)) case. What is dangerous about it?

Thank you.

+6  A: 

It's the same problem as with lock(this) - you're locking on a reference which other code has access to, so it could be locking on it too.

If you have two unrelated pieces of code locking on the same reference without intending to exclude each other, then in the best case you could lose a bit of performance due to a lack of concurrency - and in the worst case you could introduce a deadlock.

Jon Skeet
Hmm... I think I have a greater misunderstanding of the lock keyword. From your description it seems like if I have 2 locks in completely unrelated parts of my program, which lock on the same type. If one lock is taken by one thread, no thread can enter either this one or the other one?
Alex K
Exactly. They're using the same lock, even if they're unrelated bits of code. That is Bad.
Jon Skeet
+11  A: 

It's dangerous because anything can take that lock so it's difficult or impossible to prevent a deadlock situation.

There used to be an article on this ("Don't Lock Type Objects!" a Dr. GUI article) in with some comments by Rico Mariani. Apparently the article is no longer directly available, but there are 'mirrors' floating around, including at http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects.

Here's an excerpt:

The basic problem here is that you don't own the type object, and you don't know who else could access it. In general, it's a very bad idea to rely on locking an object you didn't create and don't know who else might be accessing. Doing so invites deadlock. The safest way is to only lock private objects.

But wait; it's even worse than all that. As it turns out, type objects are sometimes shared across application domains (but not across processes) in current versions of the .NET runtime. (This is generally okay since they're immutable.) That means that it's possible for ANOTHER APPLICATION running even in a different application domain (but in the same process) to deadlock your application by getting a lock on a type object you want to lock and never releasing it. And it would be easy to get access to that type object because the object has a name—the fully qualified name of the type! Remember that lock/SyncLock blocks (that's a polite word for hangs) until it can obtain a lock. It's obviously really quite bad to rely on a lock that another program or component can lock and cause you to deadlock.

Michael Burr
Though Jon Skeet was first, your reply is more informative and cleared up a confusion I had about the way the lock statement works, so you get a gold star... erm... I mean a green check box :) Thank you.
Alex K
Thank goodness for the United States Handicapper General and the 211th, 212th and 213th Amendments that require the Harrison Bergeron-like Jon Skeet to use a molasses-covered keyboard to give the rest of us a fighting chance.
Michael Burr
good answer. a common pattern we use in framework code is to have a private instance field just for locking:private object thisLock = new object();for static locks you can use a private static field:private static object staticLock = new object();
alexdej
A: 

Because the result of typeof (MyType) (which is an object of type Type) is widely accessible and other thread can lock on the same object, and hold that lock indefinitely. Then internal logic of MyType has effectively given away significant control over it's synchronization logic. This might not be an actual problem if this is intended, but coding defensively/skeptically should be your modus operandi.

gWiz
A: 

because the target of a lock is ONLY to establish a place to store the lock boolean (Am I locked or not) for other threads to look at....

The common misconception that the target of a lock is actually somehow being locked is just wrong... What is "locked" is, .... nothing, unless in methods which can access some shared memory in an unsafe manner, you write the code to look at the this lock and not proceed until it has been released... using a Type object, as a lock target is wrong because code snippets anywhere in the entire solution process space can access that type object and change the synch block that the lock boolean is stored in. Creating a locally scoped object allows you to better ensurethat only those threads and methods that can access or mess with your "at risk" shared memory can also access and/or modify the lock.

Charles Bretana
A: 

There are always exceptions to the rule and if you know a deadlock situation will not occur then go ahead and use it. Microsoft even seems to go against its own advice in its implementations in the FCL. For example, see the SyncRoot property that is public on many Microsoft classes and is intended for locking

John K
+1  A: 

I don't like the whole lock concept of C#. Seems like an architecture bag to me. they should have created an empty class [just like they did with EventArgs] (called Locker for example) which is the only lockable object. This way everybody would follow the best practice....

Or even better, to add it properties such as bool Looked {get; Set;} (or maybe just get i'm not sure)

Itay
Yeah, I think most people agree that the lock keyword was not the best choice to implement trivial thread synchronization. I have seen alternative recommendation that would have fit in nicely with the using keyword. And of course your suggestion of having a specific class called Locker (or whatever) would be acceptable as well.
Brian Gideon
XDDDDD in my account it said i got 20 points for this one, and not even one point i lost, yet it seems i was thumb down... stackoverflow's bug? :P
Itay