简体   繁体   中英

.net core BackgroundService Http Server/GRPC - Stop Method?

currently what is the best way to actually run a Http Server inside a .net core BackgroundService , ie running is easy, but how to actually correctly integrate the stopping method.

At the moment I've written the code like that:

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

before I had something like

while(!stoppingToken.IsCancellationRequested) {}
await server.ShutdownAsync()

however the performance was really really bad.

is this actually the correct way of doing it? or are there better ways? ( IApplicationLifetime )?

BackgroundService implements IHostedService . You can implement you own tiny background service, that also implements 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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