首页 > 后端开发 > C++ > 如何捕获C#中的控制台应用程序退出事件?

如何捕获C#中的控制台应用程序退出事件?

Patricia Arquette
发布: 2025-01-28 09:51:08
原创
828 人浏览过

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

优雅地处理C#

中的控制台应用程序终止

构建控制台应用程序时,适当的资源管理至关重要。 一个普遍的需求是在应用程序退出之前执行清理任务。虽然C#没有为此提供直接事件,但我们可以利用Windows API实现此功能。

>该解决方案涉及设置控制台控制处理程序以响应各种终止信号。 这允许在应用程序关闭之前执行自定义代码,以确保正确发布资源。

这是一个实用的实现:

此代码会在控制台接收终止信号时(例如Ctrl c,关闭窗口,系统关闭)时,该代码会登记一个处理程序(
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
}
登录后复制
)。

>功能执行必要的清理任务。 从处理程序返回ConsoleHandler表示事件的成功处理。 不优雅地处理事件可能会导致资源泄漏或数据损坏。ConsoleHandler>

以上是如何捕获C#中的控制台应用程序退出事件?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板