4

所以我有一个 dotnet 核心工作进程,我想在某些情况下关闭工作进程。

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
     {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("This is a worker process");
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                 if (condition == true)
                  //do something to basically shutdown the worker process with failure code.
                
                await Task.Delay(2000, stoppingToken);                
            }
        }

我怎样才能做到这一点?我试图打破循环,但这并没有真正关闭工作进程。

//----this does not work-----
//even after doing this, Ctrl-C has to be done to shutdown the worker.
if (condition == true) break; 
4

1 回答 1

9

退出 IHostedService 不会终止应用程序本身。一个应用程序可能运行多个 IHostedService,因此其中一个关闭整个应用程序是没有意义的。

要终止应用程序,托管服务类必须接受IHostApplicationLifetime实例,并在要终止应用程序时调用StopApplication 。该接口将由 DI 中间件注入:

class MyService:BackgroundService
{
    IHostApplicationLifetime _lifetime;

    public MyService(IHostApplicationLifetime lifetime)
    {
        _lifetime=lifetime;
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            ...
            if (condition == true)
            {
                   _lifeTime.StopApplication();
                   return;
            }
                 
            ...            
        }
    }

}

这将通知所有其他后台服务正常终止并导致Run()RunAsync()返回,从而退出应用程序。

投掷也不会结束应用程序

StopApplication如果服务希望进程终止,则必须确保调用该服务,例如:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    try 
    {
        ...
    }
    catch(Exception exc)
    {
        //log the exception then
        _lifetime.StopApplication();
    }

}
于 2020-10-05T15:28:54.727 回答