如何实现 asp.net core 安全优雅退出 ?

咨询区

  • AppDeveloper

我想问一个老生常谈的问题,如何可以保证程序优雅的退出,这里用 优雅 的目的是因为我想在退出之前做一些小动作。

用户场景:希望在程序退出之前可以从 Consul 上解注册, 下面是我的模板代码。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((host, config) =>
        {
        })
        .UseStartup<Service>();

回答区

  • Edward

为了能够让程序优雅的退出,你可以用 IHostApplicationLifetime 哈,它定义了很多 action 枚举,比如:启动前,启动后,停止前 等等。。。

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading;

namespace Microsoft.Extensions.Hosting
{
    /// <summary>
    /// Allows consumers to be notified of application lifetime events. This interface is not intended to be user-replaceable.
    /// </summary>
    public interface IHostApplicationLifetime
    {
        /// <summary>
        /// Triggered when the application host has fully started.
        /// </summary>
        CancellationToken ApplicationStarted { get; }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// Shutdown will block until this event completes.
        /// </summary>
        CancellationToken ApplicationStopping { get; }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// Shutdown will block until this event completes.
        /// </summary>
        CancellationToken ApplicationStopped { get; }

        /// <summary>
        /// Requests termination of the current application.
        /// </summary>
        void StopApplication();
    }
}

接下来就可以在相关枚举上注册事件啦,参考如下代码:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    var life = host.Services.GetRequiredService<IHostApplicationLifetime>();
    life.ApplicationStopped.Register(() => {
        Console.WriteLine("Application is shut down");
    });
    host.Run();
}

点评区

说实话,相见恨晚,我在项目开发中也遇到了这种情况,我的场景是需要将  asp.net core 用 后台服务 的方式承载,为了方便操作,我用了 topshelf ,官方网址:http://topshelf-project.com  类似如下代码:

public class TownCrier
{
    readonly Timer _timer;
    public TownCrier()
    {
        _timer = new Timer(1000) {AutoReset = true};
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
    }
    public void Start() { _timer.Start(); }
    public void Stop() { _timer.Stop(); }
}

public class Program
{
    public static void Main()
    {
        var rc = HostFactory.Run(x =>                                   //1
        {
            x.Service<TownCrier>(s =>                                   //2
            {
               s.ConstructUsing(name=> new TownCrier());                //3
               s.WhenStarted(tc => tc.Start());                         //4
               s.WhenStopped(tc => tc.Stop());                          //5
            });
            x.RunAsLocalSystem();                                       //6

            x.SetDescription("Sample Topshelf Host");                   //7
            x.SetDisplayName("Stuff");                                  //8
            x.SetServiceName("Stuff");                                  //9
        });                                                             //10

        var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode());  //11
        Environment.ExitCode = exitCode;
    }
}

现在看样子不需要了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值