According to the language specification lock(obj) statement;
would be compiled as:
object lockObj = obj; // (the langspec doesn't mention this var, but it wouldn't be safe without it)
Monitor.Enter(lockObj);
try
{
statement;
}
finally
{
Monitor.Exit(lockObj);
}
However, it is compiled as:
try
{
object lockObj = obj;
bool lockTaken = false;
Monitor.Enter(lockObj, ref lockTaken);
statement;
}
finally
{
if (lockTaken) Monitor.Exit(lockObj);
}
That seems to be a lot more complicated than necessary. So the question is, what's the advantage of that implementation?
Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.
A monitor is a mechanism for ensuring that only one thread at a time may be running a certain piece of code (critical section). A monitor has a lock, and only one thread at a time may acquire it. To run in certain blocks of code, a thread must have acquired the monitor.
As always, Eric Lippert has already answered this:
Fabulous Adventures In Coding: Locks and exceptions do not mix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With