Sign in to follow this  
capn_midnight

[.net] Locking resources and catching exceptions

Recommended Posts

capn_midnight    1707
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.

Share this post


Link to post
Share on other sites
capn_midnight    1707
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.

Share this post


Link to post
Share on other sites
capn_midnight    1707
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this