Throwing exception in a lock statement C# with Example



Throwing exception in a lock statement C# with Example

Following code will release the lock. There will be no problem. Behind the scenes lock statement works as try 
finally 
lock(locker) 
{ 
throw new Exception(); 
} 
More can be seen in the C# 5.0 Specification: 
A lock statement of the form 
lock (x) ... 
where x is an expression of a reference-type, is precisely equivalent to 
bool lockWasTaken = false; 
try { 
System.Threading.Monitor.Enter(x, ref   lockWasTaken); 
... 
} 
finally { 
if ( lockWasTaken) System.Threading.Monitor.Exit(x); 
} 
except that x is only evaluated once. 

0 Comment's

Comment Form

Submit Comment