![](/img/trans.png)
[英]Windows Service using .net core BackgroundService, how to gracefully stop?
[英]How to stop windows service when trhow exception? NET CORE
我在 .NET 核心 3.1 中有一个 Windows 服务的示例。
我正在生成一个故意错误以查看其行为,我的想法是当异常发生时我想调用 StopAsync 方法来停止服务,但是一旦执行 StopAsync 再次执行 ExecuteAsync 方法并且服务不会停止,像这样进入无限循环。
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.CompletedTask;
while (!stoppingToken.IsCancellationRequested)
{
try
{
int num = 233;
int result = num / 0;
//todo
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
await StopAsync(stoppingToken); //this execute, but it keeps running this ExecuteAsync method
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("stop service");
await base.StopAsync(cancellationToken);
}
ExecuteAsync 方法再次执行,服务没有停止,像这样进入无限循环。
您确定吗? StopAsync
将取消提供给ExecuteAsync
的令牌,看起来您的ExecuteAsync
方法将在这种情况下完成。
但是,主机应用程序本身将继续运行; 也许这就是你所看到的。 要在后台服务退出时关闭宿主应用程序, 您需要显式停止应用程序:
private readonly IHostApplicationLifetime _hostApplicationLifetime;
public MyBackgroundService(IHostApplicationLifetime hostApplicationLifetime) =>
_hostApplicationLifetime = hostApplicationLifetime;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
...
}
finally
{
_hostApplicationLifetime.StopApplication();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.