I created an ConsoleEventHandler based on the following link described: https://www.meziantou.net/detecting-console-closing-in-dotnet.htm
It works perfectly for me. Currently I wish it can handle SIGTERM from both Windows and Linux. Does anybody has some clue about how to optimize it in C#? The following code needs to be optimized in two parts:
- can load Kernel32 in docker. Currently it fails in "System.DllNotFoundException: Unable to load shared library 'Kernel32' or one of its dependencies. "
- Support linux system;
The source code:
class Program
{
// https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms686016.aspx
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(SetConsoleCtrlEventHandler handler, bool add);
// https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms683242.aspx
private delegate bool SetConsoleCtrlEventHandler(CtrlType sig);
private enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
static void Main(string[] args)
{
// Register the handler
SetConsoleCtrlHandler(Handler, true);
// Wait for the event
while (true)
{
Thread.Sleep(50);
}
}
private static bool Handler(CtrlType signal)
{
switch (signal)
{
case CtrlType.CTRL_BREAK_EVENT:
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
Console.WriteLine("Closing");
// TODO Cleanup resources
Environment.Exit(0);
return false;
default:
return false;
}
}
}