停止使用 DI 和用户代码托管服务的控制台应用程序

Stop console application that is using DI and a hosted service for user code

我正在构建一个控制台应用程序,它应该在几个小时后停止 运行。我使用依赖注入来获取我的服务实例,我的主要服务被注册为托管服务,作为我的代码的入口点。

应用程序完成其工作后,可执行文件应该停止 运行。如果我在服务上调用 StopAsync(),它会运行该方法但不会终止可执行文件。如何退出程序?

Program.cs

class Program
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public static void Main(string[] args)
    {
        _logger.Info($"starting execution of Program.Main()");

        CreateHostBuilder(args).Build().Run();

        _logger.Info($"finished execution of Program.Main()");
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        IConfiguration Configurations = new ConfigurationBuilder()
            .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
#if DEBUG
            .AddUserSecrets("secrets guid")
#endif
            .Build();

        return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostContext, builder) => builder.AddConfiguration(Configurations))
            .ConfigureServices(services =>
            {
                services.AddHostedService<MainService>();

                services.AddScoped<Service1>();
                services.AddScoped<Service2>();
                services.AddScoped<Service3>();

                services.AddDbContext<pig_dbContext>(options =>
                    options.UseMySql(Configurations.GetConnectionString("XXXX"), builder =>
                        builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null)));
            });
    }
}

MainService.cs

public class MainService: IHostedService
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public MainService(Service1 service1, Service2 service2, Service3 service3, IServiceProvider services, IConfiguration config)
    {
        //...
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        //This method is called by .NET when calling Host.Run()
        ///Do work...

        //This call reaches the method, but does not end execution of the application. I want the application to completely exit.
        StopAsync(new CancellationToken());
    }

我想通了:主机一直阻塞主线程,所以使用

CreateHostBuilder(args).Build().RunAsync();

解决了我的问题:)