Finally != Inevitable

142 words.

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.

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.