Possible Duplicate:
Difference between lock(locker) and lock(variable_which_I_am_using)
In all of the "thread-safe" code examples i've seen, they lock on a separate dummy object. Why cant locks be directly performed on the data in question?
Possible Duplicate:
Difference between lock(locker) and lock(variable_which_I_am_using)
In all of the "thread-safe" code examples i've seen, they lock on a separate dummy object. Why cant locks be directly performed on the data in question?
Locking on a separate private
dummy object gives you a guarantee that no one else is locking in that object.
If you lock on the data and that same piece of data is visible to the outside you lose that guarantee. For example:
public class MyObject
{
public void SharedMethod()
{
lock (this)
{
// Do stuff
}
}
}
class Program
{
static void Main(string[] args)
{
MyObject o = new MyObject();
lock (o)
{
new Thread(() =>
{
// Gets blocked 2s because of external lock
o.SharedMethod();
}).Start();
Thread.Sleep(2000);
}
}
}
Jeff Richter (author of CLR Via C#) explains why in this article on Safe Thread Synchronization.
Specifically, in that article the section "Why the Great Idea isn't So Great" answers your question.
It's actually a chapter from the book CLR Via C#.
In summary, having a private object as the "synclock" object allows your class to encapsulate and control any locking your class needs. Therefore regardless of how many clients use your class, locking is performed consistently and correctly.