最近我的项目需要在退出前保存数据到数据库,所以研究了一下。
using System;
namespace TestExit2
{
internal class Program
{
static void onProcessExit(object sender,EventArgs e)
{
Console.WriteLine("Exit");
Console.ReadLine();
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(onProcessExit);
}
}
}
这个好像只能在正常退出的时候作用。
using System;
using System.Runtime.InteropServices;
namespace TestExit2
{
internal class Program
{
[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)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
default:
Console.WriteLine(sig.ToString());
return false;
}
}
public class ConsoleExitEventArgs : EventArgs
{
public long countip { get; set; }
//public testamp_ampip db { get; set; }
}
static long cou=123;
static void onProcessExit(object sender, EventArgs e)
{
if(e!=null)
{
Console.WriteLine("ProcessExit");
Console.WriteLine(((ConsoleExitEventArgs)e).countip);
}
else
Console.WriteLine("Exit");
Console.WriteLine(cou);
//((ConsoleExitEventArgs)e).db.update_cursor_scan_amapip(((ConsoleExitEventArgs)e).countip);
//Environment.Exit(0);
}
static void Main(string[] args)
{
cou++;
AppDomain.CurrentDomain.ProcessExit += new System.EventHandler(onProcessExit);
// Some biolerplate to react to close window event, CTRL-C, kill, etc
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
while(true)
{
Console.WriteLine(cou++);
if (cou == 0xffff)
break;
}
}
}
}
参考文档: