我正在.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()
但是每次我遇到一些限制时,实现此限制的正确方法是什么?
答案 0 :(得分:1)
使用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();
}
}
}
}