.NET控制臺(tái)應(yīng)用程序退出事件在.NET中,是否有一種方法(如事件)用于檢測控制臺(tái)應(yīng)用程序何時(shí)退出?我需要清理一些線程和COM對象。我正在從控制臺(tái)應(yīng)用程序運(yùn)行一個(gè)沒有表單的消息循環(huán)。我正在使用的DCOM組件似乎要求應(yīng)用程序泵消息。我已經(jīng)嘗試向Process.GetCurrentProcess.Exited和Process.GetCurrentProcess.Disposed添加一個(gè)處理程序。我還嘗試向Application.ApplicationExit和Application.ThreadExit事件添加處理程序,但它們沒有觸發(fā)。也許那是因?yàn)槲覜]有使用表格。
3 回答

翻過高山走不出你
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是一個(gè)完整的,非常簡單的.Net解決方案,適用于所有版本的Windows。只需將其粘貼到一個(gè)新項(xiàng)目中,運(yùn)行它并嘗試CTRL-C來查看它如何處理它:
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading;namespace TestTrapCtrlC{ public class Program{ static bool exitSystem = false; #region Trap application termination [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) { Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown"); //do your cleanup here Thread.Sleep(5000); //simulate some cleanup delay Console.WriteLine("Cleanup complete"); //allow main to run off exitSystem = true; //shutdown right away so there are no lingering threads Environment.Exit(-1); return true; } #endregion static void Main(string[] args) { // Some biolerplate to react to close window event, CTRL-C, kill, etc _handler += new EventHandler(Handler); SetConsoleCtrlHandler(_handler, true); //start your multi threaded program here Program p = new Program(); p.Start(); //hold the console so it doesn’t run off the end while(!exitSystem) { Thread.Sleep(500); } } public void Start() { // start a thread and start doing some processing Console.WriteLine("Thread started, processing.."); } } }

慕少森
TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
該應(yīng)用程序是一個(gè)服務(wù)器,它只運(yùn)行直到系統(tǒng)關(guān)閉或接收到Ctrl + C或控制臺(tái)窗口關(guān)閉。
由于應(yīng)用程序的特殊性,“優(yōu)雅地”退出是不可行的。(可能是我可以編寫另一個(gè)會(huì)發(fā)送“服務(wù)器關(guān)閉”消息的應(yīng)用程序,但這對于一個(gè)應(yīng)用程序來說是過度的,而且在某些情況下仍然不夠,例如當(dāng)服務(wù)器(實(shí)際操作系統(tǒng))實(shí)際關(guān)閉時(shí)。)
由于這些情況,我添加了一個(gè)“ ConsoleCtrlHandler ”,我停止我的線程并清理我的COM對象等...
Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As BooleanPublic Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As BooleanPublic Enum CtrlTypes CTRL_C_EVENT = 0 CTRL_BREAK_EVENT CTRL_CLOSE_EVENT CTRL_LOGOFF_EVENT = 5 CTRL_SHUTDOWN_EVENTEnd EnumPublic Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean..clean up code here.End FunctionPublic Sub Main()...SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)..End Sub
這種設(shè)置似乎完美無缺。這是一個(gè)鏈接到同一件事的一些C#代碼。
- 3 回答
- 0 關(guān)注
- 1939 瀏覽
添加回答
舉報(bào)
0/150
提交
取消