![](/img/trans.png)
[英]Windows Service using .net core BackgroundService, how to gracefully stop?
[英].net core BackgroundService Http Server/GRPC - Stop Method?
当前,在.net核心BackgroundService
实际运行Http Server的最佳方法是什么,即运行很容易,但是如何正确集成停止方法。
目前,我已经编写了如下代码:
var server = new Server
{
Services = {ConnectionHandler.BindService(_vpnConnectionHandler)},
Ports = {new ServerPort("0.0.0.0", 50055, ServerCredentials.Insecure)}
};
var source = new TaskCompletionSource<bool>();
stoppingToken.Register(async () => await server.ShutdownAsync());
server.Start();
if (!stoppingToken.IsCancellationRequested)
{
await source.Task;
}
在我有类似的东西之前
while(!stoppingToken.IsCancellationRequested) {}
await server.ShutdownAsync()
但是性能真的很差。
这实际上是正确的做法吗? 还是有更好的方法? ( IApplicationLifetime
)?
BackgroundService
实现IHostedService
。 您可以实现自己的微型后台服务,该服务还实现IHostedService
:
public class YourBackgroundService : IHostedService
{
private Server _server;
public Task StartAsync(CancellationToken cancellationToken)
{
_server = new Server
{
Services = {ConnectionHandler.BindService(_vpnConnectionHandler)},
Ports = {new ServerPort("0.0.0.0", 50055, ServerCredentials.Insecure)}
};
_server.Start();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return server?.ShutdownAsync() ?? Task.CompletedTask;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.