unl*_*mit 1 c# .net-core asp.net-core-hosted-services
所以我有一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我试图跳出循环,但这并没有真正关闭工作进程。
//----this does not work-----
//even after doing this, Ctrl-C has to be done to shutdown the worker.
if (condition == true) break;
Run Code Online (Sandbox Code Playgroud)
退出 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 Code Online (Sandbox Code Playgroud)
这将通知所有其他后台服务正常终止并导致Run()
或RunAsync()
返回,从而退出应用程序。
投掷也不会结束应用程序。
StopApplication
如果要终止进程,服务必须确保被调用,例如:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
...
}
catch(Exception exc)
{
//log the exception then
_lifetime.StopApplication();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
537 次 |
最近记录: |