Home > Backend Development > C++ > How Can I Handle Console Application Exit Events in C#?

How Can I Handle Console Application Exit Events in C#?

Linda Hamilton
Release: 2025-01-28 09:47:07
Original
986 people have browsed it

How Can I Handle Console Application Exit Events in C#?

Graceful Shutdown in C# Console Applications: Handling Exit Events

Multi-threaded C# console applications require robust cleanup procedures upon termination to ensure proper resource management. While .NET doesn't offer a built-in exit event, we can leverage the Win32 API for a reliable solution.

The Absence of a Direct .NET Event

Unfortunately, the .NET framework lacks a direct event for detecting application exit.

Utilizing the Win32 API: A Practical Approach

The Win32 API's SetConsoleCtrlHandler function provides a mechanism to register a handler for various control signals, including console closure. This allows for executing custom code before the application terminates.

Code Example: Implementing a Console Exit Handler

The following code snippet demonstrates registering a handler for console close events:

using System;
using System.Runtime.InteropServices;

// ... other using statements ...

public class Program
{
    [DllImport("Kernel32.dll")]
    private static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);

    private delegate bool HandlerRoutine(CtrlTypes ctrlType);

    private enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT = 1,
        CTRL_CLOSE_EVENT = 2,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT = 6
    }

    private static bool Handler(CtrlTypes ctrlType)
    {
        Console.WriteLine("Console exit event detected: " + ctrlType);
        // Perform cleanup operations here (e.g., closing files, stopping threads)
        return true; // Indicate that the handler processed the event
    }

    public static void Main(string[] args)
    {
        SetConsoleCtrlHandler(Handler, true);
        // ... your application's main logic ...
        Console.ReadKey(); // Keep the console open until a key is pressed
    }
}
Copy after login

Important Considerations and Limitations:

This approach relies on the Windows API and may not be directly portable to non-Windows environments. The Handler function should perform all necessary cleanup tasks, such as closing files, releasing resources, and ensuring thread termination before returning true. Returning false indicates that the default system handler should be invoked. Remember to handle potential exceptions within the Handler function.

The above is the detailed content of How Can I Handle Console Application Exit Events in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template