Brans Ds
Brans Ds

Reputation: 4117

C# lock internal implementation

I know that now in C# lock is implemented in such way:

bool lockWasTaken = false;
var temp = obj;
try 
{ 
     Monitor.Enter(temp, ref lockWasTaken); 
     { 
        //body 
     } 
}
finally 
{ 
     if (lockWasTaken) 
     {
         Monitor.Exit(temp); 
      }
}

Why do we need this: var temp = obj; ?

Upvotes: 0

Views: 622

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

Simple, What if you changed the variable after the Monitor.Enter called and before Monitor.Exit?

To prevent that it takes up a copy of the variable. Even you can set the value to null also inside the lock statement but still it makes sure that it releases the lock which it taken earlier.

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239664

Because obj might be reassigned within the body of the lock code, and the code you've shown has to make sure that it calls Exit on the same object it called Enter for.

Upvotes: 1

Related Questions