.NET Core Worker 服务作为 Windows 服务在调用 StopAsync 后未停止

.NET Core Worker Service as Windows service not stopping after calling StopAsync

我有一个工作人员服务部署为 windows 服务,我在停止 windows 服务时遇到问题,它在日志中显示已停止,但当我登录到服务器时它仍然显示 运行.

public class Worker : BackgroundService
{
  private readonly ILogger<Worker> _logger;
  

  public Worker(ILogger<Worker> logger)
  {
    this._logger = logger;
  }

  public override Task StartAsync(CancellationToken cancellationToken)
  {
    _logger.LogInformation("Windows Service is Starting....   ");
    return base.StartAsync(cancellationToken);
  }
  protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  {
    //initial value coming as false
    _logger.LogInformation(string.Format("Cancellation token initial value : {0}", stoppingToken.IsCancellationRequested));

        while (!stoppingToken.IsCancellationRequested)
        {
           try
           {
              _logger.LogInformation("Starting the Process .....");
               
              //Dummy task used here, so it can cancel token.
              await Task.Delay(1000);       
         
              //Deliberately failing in the string.Format to test windows service stopping
              string.Format("Failing with exception here : {1}", "Test");
            }
           
            catch (Exception ex)
            {
              _logger.LogError(ex, ex.Message);
               var canclSrc = new CancellationTokenSource();
               canclSrc.Cancel();
               await StopAsync(canclSrc.Token);
                   
               //Cancellation token here is coming as true..
               _logger.LogInformation(string.Format("Cancellation token value : {0}", stoppingToken.IsCancellationRequested));
               _logger.LogInformation("Windows Service is stopped..");
             }
         }
    //Windows service failed and it is logging outside the while loop.
    _logger.LogInformation("Came out of while loop as windows service stopped!");
  }

 public override Task StopAsync(CancellationToken cancellationToken)
 {
   _logger.LogInformation("Stopping Windows Service...");
   return base.StopAsync(cancellationToken);
 }

它在日志中将取消标记设为 true,成功调用了 StopAsync 方法。

当我登录到服务器并看到 windows 服务显示 运行 并且 windows 服务在某处被攻击时我没有看到任何日志任何服务只是挂了..

任何关于为什么我的 windows 服务(这是一个辅助服务)即使在调用 stopAsync 时也不会在服务器上停止的任何建议。

await StopAsync(canclSrc.Token);

您的后台服务不应自行停止。

如果你想拆除你的主机(即 Win32 服务),那么你应该 call IHostApplicationLifetime.StopApplication(如我的博客所述)。像这样:

public class Worker : BackgroundService
{
  private readonly ILogger<Worker> _logger;
  private readonly IHostApplicationLifetime _hostApplicationLifetime;

  public Worker(ILogger<Worker> logger, IHostApplicationLifetime hostApplicationLifetime) => (_logger, _hostApplicationLifetime) = (logger, hostApplicationLifetime);

  protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  {
    _logger.LogInformation("Windows Service is Starting....   ");

    _logger.LogInformation(string.Format("Cancellation token initial value : {0}", stoppingToken.IsCancellationRequested));

    try
    {
      while (!stoppingToken.IsCancellationRequested)
      {
        _logger.LogInformation("Starting the Process .....");
               
        await Task.Delay(1000);       
         
        //Deliberately failing in the string.Format to test windows service stopping
        string.Format("Failing with exception here : {1}", "Test");
      }
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, ex.Message);
    }
    finally
    {
      _logger.LogInformation("Windows Service is stopped..");
      _hostApplicationLifetime.StopApplication();
    }
  }
}