Difference Between Monitor & Lock?

Goober picture Goober · May 23, 2009 · Viewed 12.4k times · Source

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

Answer

John Gietzen picture John Gietzen · May 23, 2009

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);
    }
}