Search code examples
lockingthread-synchronizationmutual-exclusion

Difference Between Monitor & Lock?


What's the difference between a monitor and a lock?

If a lock is simply an implementation of mutual exclusion, then is a monitor simply a way of making use of the waiting time inbetween method executions?

A good explanation would be really helpful thanks....

regards


Solution

  • For example in C# .NET a lock statement is equivalent to:

    Monitor.Enter(object);
    try
    {
        // Your code here...
    }
    finally
    {
        Monitor.Exit(object);
    }
    

    However, keep in mind that Monitor can also Wait() and Pulse(), which are often useful in complex multithreading situations.

    Edit: In later versions of the .NET framework, this was changed to:

    bool lockTaken = false;
    try
    {
        Monitor.Enter(object, ref lockTaken);
        // Your code here...
    }
    finally
    {
        if (lockTaken)
        {
            Monitor.Exit(object);
        }
    }