I'm setting up .net application in a windows container based on win2019 with .net 4.7.2 framework. I am seeking a way to gracefully shutdown the container but before so my app will finish some "in progress" tasks before the container is stopped. "docker stop" command just kill the container. my application is based on .net 4.7.2 and NOT .Net Core.
this is an example for what i saw when using .Net Core :
private static readonly AutoResetEvent _closing = new AutoResetEvent(false);
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
AssemblyLoadContext.Default.Unloading += Default_Unloading;
Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine(DateTime.Now.ToString());
Thread.Sleep(1000);
}
});
Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
_closing.WaitOne();
}
private static void Default_Unloading(AssemblyLoadContext obj)
{
Console.WriteLine("unload");
}
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("process exit");
}
protected static void OnExit(object sender, ConsoleCancelEventArgs args)
{
Console.WriteLine("Exit");
_closing.Set();
}
Since the AssemblyLoadContext is supported only in .Net Core i tried to use only AppDomain option but with no luck. the container is always shutdown with no option to control its timing and to close my "in progress" application tasks.
i've found the answer here: .NET Console Application Exit Event
when calling to "docker stop -t [timoutTime in seconds]" it trigger Ctrl+C event that trigger my cleanup code.