Throwing exception in a lock statement
suggest changeFollowing 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents