Jump to content
  • Advertisement
Sign in to follow this  
capn_midnight

[.net] Locking resources and catching exceptions

This topic is 4099 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Yeah, "finally" can be your best friend at times. It's really there *imo* for clean up purposes like the example you gave.

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!