我有一个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;
Environment.FailFast
,但这会跳过所有清理工作,所以最好将退出的负担转移到最高层面(捕获异常、记录日志,然后使用Environment.Exit
)。 - Jeroen MostertCancellationTokenSource
?如果是后者,另一种方法是调用Cancel
。 - Igor