Home >Backend Development >C++ >How Can I Capture Console Application Exit Events in C#?
Gracefully Handling Console Application Termination in C#
Proper resource management is paramount when building console applications. A common need is to execute cleanup tasks before the application exits. While C# doesn't offer a direct event for this, we can leverage the Windows API to achieve this functionality.
The solution involves setting a console control handler to respond to various termination signals. This allows for executing custom code before the application shuts down, ensuring resources are released correctly.
Here's a practical implementation:
<code class="language-csharp">using System; using System.Runtime.InteropServices; // Import the necessary Windows API function [DllImport("Kernel32.dll")] private static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add); // Delegate type for the handler routine private delegate bool HandlerRoutine(CtrlTypes ctrlType); // Enumeration of control types enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT = 1, CTRL_CLOSE_EVENT = 2, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT = 6 } // Our handler routine private static bool ConsoleHandler(CtrlTypes sig) { // Perform cleanup actions here, such as closing files or releasing resources Console.WriteLine("Console application is shutting down..."); // ... your cleanup code ... return true; // Indicate that the handler processed the event } static void Main(string[] args) { // Set the console control handler SetConsoleCtrlHandler(ConsoleHandler, true); // Main application logic Console.WriteLine("Console application running..."); Console.ReadKey(); // Keep the console open until a key is pressed }</code>
This code registers a handler (ConsoleHandler
) that's called when the console receives a termination signal (e.g., Ctrl C, closing the window, system shutdown). The ConsoleHandler
function performs the necessary cleanup tasks. Returning true
from the handler signifies successful processing of the event. Failure to handle the event gracefully might lead to resource leaks or data corruption.
The above is the detailed content of How Can I Capture Console Application Exit Events in C#?. For more information, please follow other related articles on the PHP Chinese website!