Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of Monitor.Enter(object, ref bool) over Monitor.Enter(object)?

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?

like image 887
Wormbo Avatar asked Jun 07 '12 15:06

Wormbo


People also ask

What is the difference between lock and monitor in C#?

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.

What is Monitor in c#?

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.


1 Answers

As always, Eric Lippert has already answered this:

Fabulous Adventures In Coding: Locks and exceptions do not mix

like image 87
Nick Butler Avatar answered Oct 06 '22 11:10

Nick Butler