try{
lock(someObject){
// an operation throws an exception
}
}
catch(Exception thatException){
// has someObject been unlocked
}
// what about now?
This issue recently came up between a developer and me. She is worried that someObject won't get unlocked. I think that someObject will be unlocked as soon as the exception is caught, as the lock block will be out of scope.
[.net] Locking resources and catching exceptions
In C#,
Ah, I've found the answer. In the C# language specification 1.2, section 8.12,
so, if "..." throws an exception, the finally block will execute and make sure that the lock is released.
Quote:
A lock statement of the formlock (x) ...
where x is an expression of a reference-type, is precisely equivalent toSystem.Threading.Monitor.Enter(x);try { ...}finally { System.Threading.Monitor.Exit(x);}
except that x is only evaluated once.
so, if "..." throws an exception, the finally block will execute and make sure that the lock is released.
Yeah, "finally" can be your best friend at times. It's really there *imo* for clean up purposes like the example you gave.
Quote:Original post by Scylexan
Yeah, "finally" can be your best friend at times. It's really there *imo* for clean up purposes like the example you gave.
well, in this case the "finally" block is implemented behind the scenes by the lock. That was the issue at hand, would failing inside a lock clean up properly, or would we have to manually include the finally block. The spec shows that lock cleans up after itself.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement