[.net] Locking resources and catching exceptions

Started by
2 comments, last by capn_midnight 17 years ago
In C#,

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.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

Advertisement
Ah, I've found the answer. In the C# language specification 1.2, section 8.12,
Quote:
A lock statement of the form
lock (x) ...

where x is an expression of a reference-type, is precisely equivalent to
System.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.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

Yeah, "finally" can be your best friend at times. It's really there *imo* for clean up purposes like the example you gave.
STUMP - http://scyanidegaming.com
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.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

This topic is closed to new replies.

Advertisement