我是一名中文翻译助手,以下是翻译结果:
我正在使用.NET Core 3.0中的服务工作者模板。 我想要做的是,只有当我的参数“ExecuteOnce”在appsettings.json中设置为true时,才执行此服务。
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()
但每次都遇到了一些限制,正确的实现方式是什么?