多線程C#控制台應用程序在終止後需要強大的清理程序,以確保適當的資源管理。 雖然.NET不提供內置退出活動,但我們可以利用Win32 API來獲得可靠的解決方案。
> 沒有直接.NET事件
不幸的是,.NET框架缺少用於檢測應用程序退出的直接事件。
win32 API的
函數提供了一種機制,可以註冊用於各種控制信號的處理程序,包括控制台閉合。這允許在應用程序終止之前執行自定義代碼。 >
>代碼示例:實現控制台退出處理程序SetConsoleCtrlHandler
>
重要的考慮和局限性:
>
此方法依賴於Windows API,並且可能無法直接移植到非窗口環境中。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 } }
之前確保線程終止。 返回表示應調用默認系統處理程序。 請記住要處理>函數中的潛在異常。
以上是如何處理C#中的控制台應用程序退出事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!