繁体   English   中英

.net核心BackgroundService Http Server / GRPC-停止方法?

[英].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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM