Graceful shutdown with Generic Host in .NET Core 2.1

前端 未结 3 1393
时光取名叫无心
时光取名叫无心 2020-12-05 15:17

.NET Core 2.1 introduced new Generic Host, which allows to host non-HTTP workloads with all benefits of Web Host. Currently, there is no much information and recipes with it

3条回答
  •  臣服心动
    2020-12-05 15:43

    In Startup.cs, you can terminate the application with the Kill() method of the current process:

            public void Configure(IHostApplicationLifetime appLifetime)
            {
                appLifetime.ApplicationStarted.Register(() =>
                {
                    Console.WriteLine("Press Ctrl+C to shut down.");
                });
    
                appLifetime.ApplicationStopped.Register(() =>
                {
                    Console.WriteLine("Shutting down...");
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                });
            }
    

    Program.cs

    Don't forget to use UseConsoleLifetime() while building the host.

    Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);
    

提交回复
热议问题