通过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;
}