Throwing exception in a lock statement

suggest change

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.

Feedback about page:

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



Table Of Contents