Search code examples
c#multithreadingconsole-applicationterminatefinally

Is there a way to get all finally blocks across all threads to run when handling Ctrl+C in a Console Application


I have a console app that I want to be able to exit via ctrl+c. In my codebase/external libraries there are types which absolutely need their Dispose/Close() methods called for cleanup.

The suggested question in the comments is about how to trap the ctrl+c event. I already know that I can do this:

Console.CancelKeyPress+= ... obj.Close()/obj.Dispose()

The issue is that I have to remember to do this before every using block.

Is there a general way - ideally ONE event handler for CancelKeyPress that I register in the root for the whole application that somehow forces finally blocks across all threads to run?


Solution

  • Perhaps the way to go here is to switch your code to using the async/await approach, and create a CancellationTokenSource that you trigger from CancelKeyPress; now you have one central well-known pattern that can flow (via CancellationToken) through your code. Any inbuilt/library async methods will typically already support cancellation, and it isn't hard to implement in your own code, if needed, either by explicit periodic testing, or by registering as a callback.