Difference Between Monitor & Lock?
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);
}
}
They're related. For example, in C# the lock statement is a simple try-finally wrapper around entering a Monitor and exiting one when done.