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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-28 10:07:121001browse

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

Capture the console application in C#to exit the incident

In multi -threaded console applications, the termination of seamless programs may be a challenge. Some threads may monitor specific conditions and start the program closed at any given time. In order to ensure correct cleaning and resource release, developers usually look for built -in events triggered before the program closure.

A method to capture the console withdrawing is to process the procedure through custom events. Using the

function of the Windows API, you can install an event processing program to intercept various exit events, such as shutdown, shutdown or user interruption.

SetConsoleCtrlHandler The following code fragment demonstrates this technology:

Method provides a method of filtering the type of event that should trigger the cleaning code. In this example, we handle the console closure, system shutdown, and user interruption (CTRL C) incident. Note that indicates that the exit signal has been successfully processed, and the procedure allows the program to exit elegantly;
<code class="language-csharp">[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;

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

private static bool Handler(CtrlType sig)
{
    //在此处添加您的清理代码
    switch (sig)
    {
        case CtrlType.CTRL_C_EVENT:
        case CtrlType.CTRL_LOGOFF_EVENT:
        case CtrlType.CTRL_SHUTDOWN_EVENT:
        case CtrlType.CTRL_CLOSE_EVENT:
            //执行清理操作
            Console.WriteLine("执行清理操作...");
            return true; //表示已处理事件
        default:
            return false; //表示未处理事件
    }
}

static void Main(string[] args)
{
    // 注册事件处理程序
    _handler += new EventHandler(Handler);
    SetConsoleCtrlHandler(_handler, true);
    //  ...您的应用程序主代码...
    Console.WriteLine("程序运行中...");
    Console.ReadKey(); // 保持控制台窗口打开,直到用户按下按键
}</code>
means that it is not processed, and the system will continue to perform the default exit operation.

Handler It is worth noting that this solution may encounter restrictions on certain operating systems (especially Windows 7). If you encounter problems, please refer to the method of exiting the incident of online resources and other processing consoles. In order to ensure the robustness of the code, it is recommended to add an error processing mechanism to the return true; method, such as the TRY-CATCH block to capture possible abnormalities. return false;

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

Statement:
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
Previous article:libv is twoNext article:libv is two