我如何在 .net core 3.0 中执行一次工作者服务?

How can i execute a worker service once in .net core 3.0?

我在 .net core 3.0 中使用服务工作者模板。 我想做的是仅在我的参数 "ExecuteOnce" 设置为 true 时执行此服务一次 在 appsettings.json .

Program.cs :

public class Program
    {
        public static IServiceProvider Services { get; set; }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostContext, config) =>
                {
                    if (hostContext.HostingEnvironment.IsProduction())
                        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                    else
                        config.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);

                    config.SetBasePath(Directory.GetCurrentDirectory());
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
        public static void Main(string[] args)
        {
                CreateHostBuilder(args).Build().Run();
        }
    }

Worker.cs :

public class Worker : BackgroundService
    {
        private readonly IConfiguration _configuration;
        public Worker(ILogger<Worker> logger, IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken); ;
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // Bit of logic here...

                if (_configuration.GetValue<bool>("TaskConfig:ExecuteOnce"))
                    // TODO HERE : stop this service
                else
                    await Task.Delay(_configuration.GetValue<int>("TaskConfig:TaskDelayMs"), new CancellationToken());
            }
        }
    }

我试过: -等待 Task.TaskCompleted -打破循环 -调用 StopAsync()

但是每次我偶然发现一些限制,实现它的正确方法是什么?

使用 IHostApplicationLifetime - 通过它您可以告诉您的应用程序自行关闭。

public class Worker : BackgroundService
{
    private readonly IHostApplicationLifetime _hostLifetime;

    public Worker(IHostApplicationLifetime hostLifetime) 
    {
        _hostLifetime = hostLifetime;    
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)
        {
            DoWork();
            if (RunOnlyOnce())
            {
                _hostLifetime.StopApplication();
            }
        }
    }
}