Click here to Skip to main content
15,916,600 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hello All ,

I was readinf the lock concept and find that there is problem with lock(this) or lock(public type).
what is the problem doing like that ?

Please explain me with an example

A good starting point for research is the documentation[^]. I think you would be surprised at the information available in MSDN.

Share this answer
The problem with Lock(this) and Lock(type) is that these objects are public, so an external code could lock on them. So if your class is named YourClass, I can make a code like this:

YourClass obj = new YourClass();<br />lock(obj){ ... }<br />

And that would probably deadlock your internal code. Same problem for a public type. Since it is commom to lock an object that you want to protect, it's not too dificult for a code like this to happen.

The best approach is to create an object just for locking on it, instead of locking the class object. Make this locking object "static" and you get the same effect of locking a type.

Share this answer
The answer provided by Leonardo Muzzi (this one)[^] is correct.

My advice adds to this: Therefore, most universal simple way to lock data on some type's instance is to declare non-static private lock object:

private object LockObject = new object();
lock (this.LockObject) {/*...*/}

There can be cases when some portions of data your data class are completely independent, so you don't need to interlock between them, but need to lock each portion. Then, do it separately, by having as many lock objects as the number of those independent portions of data.

Finally, lock construct itself in by far not a the general case. There are very typical cases when you need different access when you read data from your data type instance or you write to it. In particular, it is very usual that there are many reads, much less writes. In this case, use System.Threading.ReaderWriterLockSlim (see Microsoft documentation on the topic). To target .NET Framework v.2.0, another (presently obsolete) type is needed: System.Threading.ReaderWriterLock, but performance is not as good.
Share this answer
Espen Harlinn 26-Feb-11 11:00am    
Good reply - a 5
Sergey Alexandrovich Kryukov 26-Feb-11 19:49pm    
Ah, to lock(this) or not lock(this) -- it is a question :-)
Thank you, Espen.

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900