Friday, September 19, 2008

Finally != Inevitable

For future reference: I had always heard that there were cases where finally blocks were not run. The other day I actually witnessed one of those situations: In a .NET console app, if you hit CTRL-C to exit the application, finally blocks are not executed. Fortunately garbage collection will still handle standard cleanup of objects for you (at least I assume so). But if you need to do something special you have to use the System.Console.CancelKeyPress event, like so:

System.Console.CancelKeyPress += delegate { Cleanup(); };

Be careful because it runs in a separate thread -- the main thread is not interrupted and won't actually stop until the CancelKeyPress handler returns.

Unfortunately, I found no way to handle the situation where the user clicks the close button (the red X) on the console window. It skips both CancelKeyPress and all the finally blocks.

Post comments at http://thomaskrehbiel.com/tech.