I am using .NET 7 and in that I am implementing BackgroundService. While implementing BackgroundService I want to log when service started and when service stopped. But I am not able to log when service stopped.
Following is my code -
public class BackgroundWorkerService : BackgroundService
{
readonly ILogger<BackgroundWorkerService> _logger;
public BackgroundWorkerService(ILogger<BackgroundWorkerService> logger)
{
_logger = logger;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service Started");
while (stoppingToken.IsCancellationRequested is false)
{
_logger.LogInformation("Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
In this above code somewhere I want to put this line -
_logger.LogInformation("Service Stopped");
But when I am writing this above line in while loop or after the while loop. And then running my website and then closing it, "Service Stopped" is not getting logged in console. What should I do ?
What I tried -
1.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service Started");
while (stoppingToken.IsCancellationRequested is false)
{
_logger.LogInformation("Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
_logger.LogInformation("Service Stopped");
}
2.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service Started");
while (stoppingToken.IsCancellationRequested is false)
{
_logger.LogInformation("Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
if (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Service Stopped");
}
}
3.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service Started");
while (stoppingToken.IsCancellationRequested is false)
{
_logger.LogInformation("Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
if (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Service Stopped");
}
}
}
4.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service Started");
while (stoppingToken.IsCancellationRequested is false)
{
_logger.LogInformation("Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
public async override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service Stopped");
await base.StopAsync(cancellationToken);
}