#if DEBUG
//Win退出程序的监听
[System.Runtime.InteropServices.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)
{
log4net.LogManager.GetLogger("WorldServer").Debug("-*** 退 出 进 程 ***-");
WorldServer.Instance().SaveAllPlayerData();
//do your cleanup here
Thread.Sleep(1000); //simulate some cleanup delay
//shutdown right away so there are no lingering threads
Environment.Exit(-1);
return true;
}
//win退出程序的监听事件
void Exit()
{
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
}
#else
//Unix退出程序的监听
public class UnixExitSignal
{
UnixSignal[] signals = new UnixSignal[]{
new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
new UnixSignal(Mono.Unix.Native.Signum.SIGUSR1)
};
public UnixExitSignal()
{
log4net.LogManager.GetLogger("WorldServer").Debug("-*** UnixExitSignal ***-");
Task.Factory.StartNew(() =>
{
int index = UnixSignal.WaitAny(signals, -1);
log4net.LogManager.GetLogger("WorldServer").Debug("-*** 退 出 进 程 ***-Linux");
WorldServer.Instance().SaveAllPlayerData();
});
}
}
//Unix退出程序的监听
void Exit()
{
UnixExitSignal unixExitSignal = new UnixExitSignal();
}
#endif
win和unix监听程序关闭的代码(可在关闭前DoSomething)
最新推荐文章于 2022-08-02 08:14:53 发布