.NET CORE WORKER服务作为Windows服务致电PostAsync之后不停止
我有一个工作人员服务部署为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的背景服务不应停止。
如果您想拆除主人(即Win32服务),则应调用
ihostapplicationlifetime.stopapplication
(如我的博客上所述)。这样的事情: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:我会坚持 Microsoft's示例使用
emoverition.exit(1)
:如果您在应用程序中使用自己的取消令牌来发出重新启动的信号,则:
:
当使用
_HostApplicationLifeTime时 .stopapplication();
Windows Service Manager在配置以重新启动错误时不会重新启动服务,因为它没有获得非零退出代码。从我的测试中:
emoverition.exit(1)
必须在backgroundService
executeasync
退出之前完成。什么 从我的测试中起作用:
main
返回非零INT。Main
停止之后。RunAsync
方法。emoveruct.exitcode = 1
executeasync
返回。我还没有查看Microsoft的Dotnet运行时源,以了解为什么是这样的。
来自 https:///blog.stephencleary.com/2020/2020/06 /ServiceBase-gotcha-recovery-actions.html :
设置
servicelifetime.exitcode = -1
可能有效(我尚未对此进行测试)。但是,正如我在emoverion.exitCode = -1
不起作用之前所说的。注意servicelifetime.exitcode = -1
不在Windows中时抛出。此外,上述问题是当executeasync退出时,Kestrel保持运行。
正如从同一博客指出的那样:
https:https:// blog。 stephencleary.com/2020/06/backgroundService-gotcha-application-lifetime.html
这就是为什么我更喜欢
emoverial.exit.exit(1)
至少在我脱离使用Windows Services之前。I'd stick with Microsoft's example using
Environment.Exit(1)
:If you're using your own cancellation tokens in the app to signal it's time to restart, then:
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 beforeBackgroundService
ExecuteAsync
exits.What doesn't work from my testing:
Main
.Main
after kestrel stops.RunAsync
method.Environment.ExitCode = 1
beforeExecuteAsync
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:
Setting
serviceLifetime.ExitCode = -1
might work (I haven't tested this). However, as I stated beforeEnvironment.ExitCode = -1
doesn't work. NoteserviceLifetime.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
Which is why I prefer
Environment.Exit(1)
at least until I get away from using windows services.