My original code is such like
Object mylock = new object();
void Test()
{
lock(mylock)
{
}
}
Compiled into the following code
void Test
{
object obj = mylock; // add a temporary variable
bool lockTaken = false;
try
{
Monitor.Enter(obj, ref lockTaken);
}
finally
{
if (lockTaken)
{
Monitor.Exit(obj);
}
}
}
I want to know why add a temporary variable rather than use original variable directly as follows.
void Test
{
bool lockTaken = false;
try
{
Monitor.Enter(mylock, ref lockTaken); // use original variable directly
}
finally
{
if (lockTaken)
{
Monitor.Exit(mylock); // use original variable directly
}
}
}