Throwing exception in a lock statement

suggest change

The following code releases the lock. Behind the scenes, a lock statement works as a 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents