[英]How to gracefully shutdown regular .net application in docker container
我正在基於win2019和.net 4.7.2框架的windows容器中設置.net應用程序。 我正在尋找一種方法來優雅地關閉容器,但在此之前,我的應用程序將在容器停止之前完成一些“進行中”任務。 “docker stop”命令只是殺了容器。 我的應用程序基於.net 4.7.2和NOT .Net Core。
這是我在使用.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();
}
由於僅在.Net Core中支持AssemblyLoadContext,我試圖僅使用AppDomain選項,但沒有運氣。 容器總是關閉,沒有選項來控制其時間並關閉我的“進行中”應用程序任務。
我在這里找到了答案: .NET控制台應用程序退出事件
當調用“docker stop -t [timoutTime in seconds]”時,它會觸發Ctrl + C事件,觸發我的清理代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.