.NET CORE WORKER服务作为Windows服务致电PostAsync之后不停止

发布于 2025-01-30 16:31:01 字数 2221 浏览 5 评论 0原文

我有一个工作人员服务部署为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);
 }

它在日志中提供了取消令牌,成功地调用了stopasync方法。

它正在显示运行,并且Windows服务被击中在我看不到的任何登录的地方。

当我登录服务器并查看Windows服务时, 即使调用了StopAsync,也不会停止服务器上。

I have a worker service deployed as windows service and I am having problem stopping windows services, it shows stopped from the logs but when I logon to the server it still says running.

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);
 }

It is giving cancellation token as true in the logs, successfully calling the StopAsync method.

When I login into the server and see the windows service it is showing running and the windows service got struck somewhere I don't see any logs anything the service just hungs..

Any suggestion on why my windows service (which is a worker service) is not stopping on the server even when stopAsync is invoked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄荷港 2025-02-06 16:31:01

等待stopAsync(canclsrc.token);

您的背景服务不应停止。

如果您想拆除主人(即Win32服务),则应调用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();
    }
  }
}

await StopAsync(canclSrc.Token);

Your background service shouldn't stop itself.

If you want to tear down your host (i.e., the Win32 Service), then you should call IHostApplicationLifetime.StopApplication (as described on my blog). Something like this:

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();
    }
  }
}
追星践月 2025-02-06 16:31:01

我会坚持 Microsoft's示例使用emoverition.exit(1)

namespace App.WindowsService;

public sealed class WindowsBackgroundService : BackgroundService
{
    private readonly JokeService _jokeService;
    private readonly ILogger<WindowsBackgroundService> _logger;

    public WindowsBackgroundService(
        JokeService jokeService,
        ILogger<WindowsBackgroundService> logger) =>
        (_jokeService, _logger) = (jokeService, logger);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                string joke = _jokeService.GetJoke();
                _logger.LogWarning("{Joke}", joke);

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
        catch (TaskCanceledException)
        {
            // When the stopping token is canceled, for example, a call made from services.msc,
            // we shouldn't exit with a non-zero exit code. In other words, this is expected...
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "{Message}", ex.Message);

            // Terminates this process and returns an exit code to the operating system.
            // This is required to avoid the 'BackgroundServiceExceptionBehavior', which
            // performs one of two scenarios:
            // 1. When set to "Ignore": will do nothing at all, errors cause zombie services.
            // 2. When set to "StopHost": will cleanly stop the host, and log errors.
            //
            // In order for the Windows Service Management system to leverage configured
            // recovery options, we need to terminate the process with a non-zero exit code.
            Environment.Exit(1);
        }
    }
}

如果您在应用程序中使用自己的取消令牌来发出重新启动的信号,则:

try
{
    // Implementation
}
catch (TaskCanceledException ex)
{
    // perhaps log debug / trace
}
catch (Exception ex)
{
    // log error
}
finally
{
    // Note that `stoppingToken.IsCancellationRequested` being true means the service was
    // manually stopped using services.msc, so returning a non-zero exit code is not desired.
    if (!stoppingToken.IsCancellationRequested)
        Environment.Exit(1);
}

当使用_HostApplicationLifeTime时 .stopapplication(); Windows Service Manager在配置以重新启动错误时不会重新启动服务,因为它没有获得非零退出代码。

从我的测试中:

emoverition.exit(1)必须在backgroundService executeasync退出之前完成。

什么 从我的测试中起作用:

  • main返回非零INT。
  • Environment.exit(1)在Main停止之后。
  • 取消取消令牌传递给Kestrel的RunAsync方法。
  • 设置emoveruct.exitcode = 1 executeasync返回。

我还没有查看Microsoft的Dotnet运行时源,以了解为什么是这样的。

来自 https:///blog.stephencleary.com/2020/2020/06 /ServiceBase-gotcha-recovery-actions.html

public class MyBackgroundService : BackgroundService
{
  private readonly IHostLifetime _hostLifetime;
  public MyBackgroundService(IHostLifetime hostLifetime) =>
      _hostLifetime = hostLifetime;

  protected override Task ExecuteAsync(CancellationToken stoppingToken)
  {
    try
    {
      // Implementation
    }
    catch (Exception)
    {
      if (_hostLifetime is ServiceBase serviceLifetime)
        serviceLifetime.ExitCode = -1;
      else
        Environment.ExitCode = -1;
    }
  }
}

设置servicelifetime.exitcode = -1可能有效(我尚未对此进行测试)。但是,正如我在emoverion.exitCode = -1不起作用之前所说的。注意servicelifetime.exitcode = -1不在Windows中时抛出。

此外,上述问题是当executeasync退出时,Kestrel保持运行。

正如从同一博客指出的那样:

https:https:// blog。 stephencleary.com/2020/06/backgroundService-gotcha-application-lifetime.html

public class MyBackgroundService : BackgroundService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;
    public MyBackgroundService(IHostApplicationLifetime hostApplicationLifetime) =>
        _hostApplicationLifetime = hostApplicationLifetime;

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            // Implementation
        }
        finally
        {
            _hostApplicationLifetime.StopApplication();
        }
    }
}

这就是为什么我更喜欢emoverial.exit.exit(1)至少在我脱离使用Windows Services之前。

I'd stick with Microsoft's example using Environment.Exit(1):

namespace App.WindowsService;

public sealed class WindowsBackgroundService : BackgroundService
{
    private readonly JokeService _jokeService;
    private readonly ILogger<WindowsBackgroundService> _logger;

    public WindowsBackgroundService(
        JokeService jokeService,
        ILogger<WindowsBackgroundService> logger) =>
        (_jokeService, _logger) = (jokeService, logger);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                string joke = _jokeService.GetJoke();
                _logger.LogWarning("{Joke}", joke);

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
        catch (TaskCanceledException)
        {
            // When the stopping token is canceled, for example, a call made from services.msc,
            // we shouldn't exit with a non-zero exit code. In other words, this is expected...
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "{Message}", ex.Message);

            // Terminates this process and returns an exit code to the operating system.
            // This is required to avoid the 'BackgroundServiceExceptionBehavior', which
            // performs one of two scenarios:
            // 1. When set to "Ignore": will do nothing at all, errors cause zombie services.
            // 2. When set to "StopHost": will cleanly stop the host, and log errors.
            //
            // In order for the Windows Service Management system to leverage configured
            // recovery options, we need to terminate the process with a non-zero exit code.
            Environment.Exit(1);
        }
    }
}

If you're using your own cancellation tokens in the app to signal it's time to restart, then:

try
{
    // Implementation
}
catch (TaskCanceledException ex)
{
    // perhaps log debug / trace
}
catch (Exception ex)
{
    // log error
}
finally
{
    // Note that `stoppingToken.IsCancellationRequested` being true means the service was
    // manually stopped using services.msc, so returning a non-zero exit code is not desired.
    if (!stoppingToken.IsCancellationRequested)
        Environment.Exit(1);
}

Here's why:

When using _hostApplicationLifetime.StopApplication(); The windows service manager will not restart the service when configured to restart on error because it's not getting a non-zero exit code.

From my testing:

Environment.Exit(1) must be done before BackgroundService ExecuteAsync exits.

What doesn't work from my testing:

  • returning non-zero int from Main.
  • Environment.Exit(1) in Main after kestrel stops.
  • Canceling a cancellation token passed to kestrel's RunAsync method.
  • Setting Environment.ExitCode = 1 before ExecuteAsync returns.

I haven't looked at Microsoft's dotnet runtime source to see why the above is the case.

from https://blog.stephencleary.com/2020/06/servicebase-gotcha-recovery-actions.html:

public class MyBackgroundService : BackgroundService
{
  private readonly IHostLifetime _hostLifetime;
  public MyBackgroundService(IHostLifetime hostLifetime) =>
      _hostLifetime = hostLifetime;

  protected override Task ExecuteAsync(CancellationToken stoppingToken)
  {
    try
    {
      // Implementation
    }
    catch (Exception)
    {
      if (_hostLifetime is ServiceBase serviceLifetime)
        serviceLifetime.ExitCode = -1;
      else
        Environment.ExitCode = -1;
    }
  }
}

Setting serviceLifetime.ExitCode = -1 might work (I haven't tested this). However, as I stated before Environment.ExitCode = -1 doesn't work. Note serviceLifetime.ExitCode = -1 throws when not in Windows.

In addition, a problem with the above is kestrel keeps running when ExecuteAsync exits.

As pointed out from the same blog:

https://blog.stephencleary.com/2020/06/backgroundservice-gotcha-application-lifetime.html

public class MyBackgroundService : BackgroundService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;
    public MyBackgroundService(IHostApplicationLifetime hostApplicationLifetime) =>
        _hostApplicationLifetime = hostApplicationLifetime;

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            // Implementation
        }
        finally
        {
            _hostApplicationLifetime.StopApplication();
        }
    }
}

Which is why I prefer Environment.Exit(1) at least until I get away from using windows services.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文