views:

170

answers:

3

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?

+11  A: 

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);
        }
    }
}
João Angelo
Nice example of the problem.
RichardOD
I think i get it. If you have a separate dummy object then by locking on an object you want to use you're not preventing it from doing anything?
RCIX
I mean, when you try to call a method on that object that needs to clock something.
RCIX
Yes, the main advantage in locking on private dummy objects is that you know that only your code will lock on those objects and that way no external code will affect your internal synchronization mechanisms.
João Angelo
+2  A: 

There's some great stuff on this on Eric Gunnerson's blog. See here and here.

RichardOD
+6  A: 

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.

Ash
+1. I was going to point out his book, but this article is effectively the same!
RichardOD