經過IL發現代碼被優化優化
#region kernel32 //委託 private delegate int ConsoleCtrlDelegate(int CtrlType); //winApi [DllImport("kernel32.dll")] private static extern int SetConsoleCtrlHandler(ConsoleCtrlDelegate ctrlDelegate, int Add); //volatile static 變量防止優化 volatile static ConsoleCtrlDelegate consoleCtrlDelegate = new ConsoleCtrlDelegate(HandlerRoutine); #endregion static void Main(string[] args) { int isSuccess = SetConsoleCtrlHandler(consoleCtrlDelegate, 1); //...... } /// <summary> /// 釋放Service資源 /// </summary> /// <param name="ctrlType"></param> /// <returns></returns> private static int HandlerRoutine(int ctrlType) { switch (ctrlType) { case 0: dispose(); break; case 2: dispose(); break; } return 0; }