gpt4 book ai didi

c# - 我如何在 .net core 3.0 中执行一次 worker 服务?

转载 作者:行者123 更新时间:2023-12-05 08:51:40 24 4
gpt4 key购买 nike

我在 .net core 3.0 中使用服务 worker 模板。如果我的参数“ExecuteOnce”设置为 true,我想做的是仅执行一次此服务在 appsettings.json 中。

程序.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());
}
}
}

我试过:-等待任务.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();
}
}
}
}

关于c# - 我如何在 .net core 3.0 中执行一次 worker 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59092823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com