none
lock(new object()) RRS feed

  • Question

  • Anything wrong with locking like so?

    lock(new object())
    {
            // do something
    }


    It was suggested that I avoid doing that, and instead do the following, but I didn't follow the reasoning:

    object o = new object();

    lock(o)
    {
            // do something
    }
    Monday, June 2, 2008 9:52 PM

Answers

  • Locks ensure mutual exclusion -- no more than one thread may hold the lock at the same time.  The lock is identified with a specific object instance.  You are creating a new object to lock on every time and you don't have any way to inform any other thread to lock on that exact same object instance.  Therefore, your locking is useless.

    Typically, the lock object is declared as a member variable (such as private object m_Lock = new object()).



    Monday, June 2, 2008 11:46 PM