在IHostedService实现中,需要注册控制台取消令牌(CancellationToken)以便在收到CTRL+C时执行清理操作。如果未执行此操作,则应用程序将直接关闭,可能导致数据损失或其他问题。以下是一个示例:
public class MyService : IHostedService
{
private readonly ILogger<MyService> _logger;
private readonly CancellationTokenSource _cancellationTokenSource;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
_cancellationTokenSource = new CancellationTokenSource();
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MyService is starting.");
// Register the cancellation token from the console
Console.CancelKeyPress += (sender, args) =>
{
args.Cancel = true;
_cancellationTokenSource.Cancel();
_logger.LogInformation("CTRL+C received. Stopping MyService.");
};
// Do some work
return Task.Run(async () =>
{
while (!_cancellationTokenSource.Token.IsCancellationRequested)
{
_logger.LogInformation("MyService is working.");
await Task.Delay(TimeSpan.FromSeconds(1), _cancellationTokenSource.Token);
}
}, _cancellationTokenSource.Token);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MyService is stopping.");
// Clean up resources
// ...
// Wait for the work to complete
await Task.CompletedTask;
}
}
在这个示例中,我们注册了Console.CancelKeyPress事件,以便在收到CTRL+C时调用CancellationTokenSource的Cancel方法。这将触发StopAsync方法的调用,允许我们执行清理操作并停止服务。请注意,我们还在Task.Run中使用了CancellationTokenSource.Token,以便在取消时终止工作线程。
使用此方法,我们可以确保IHostedService能够正确地响应CTRL+C,并在关闭应用程序时执行必要的清理操作。