OnlineSalesAutoCrop/Api/OnlineSalesAutoCrop.WS/WorkerService.cs

41 lines
1.5 KiB
C#
Raw Normal View History

2026-06-14 12:46:29 +06:00
namespace OnlineSalesAutoCrop.WS
{
public class WorkerService(ILoggerFactory loggerFactory) : BackgroundService
{
public ILogger Logger { get; } = loggerFactory.CreateLogger<WorkerService>();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
Logger.LogInformation("OnlineSalesAutoCrop_WS is starting.");
stoppingToken.Register(() => Logger.LogInformation("OnlineSalesAutoCrop_WS is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
Logger.LogInformation("OnlineSalesAutoCrop_WS has stopped.");
}
catch (OperationCanceledException)
{
// When the stopping token is canceled, for example, a call made from services.msc,
// we shouldn't exit with a non-zero exit code. In other words, this is expected...
}
catch (Exception ex)
{
Logger.LogError(ex, "{Message}", ex.Message);
// Terminates this process and returns an exit code to the operating system.
// This is required to avoid the 'BackgroundServiceExceptionBehavior', which
// performs one of two scenarios:
// 1. When set to "Ignore": will do nothing at all, errors cause zombie services.
// 2. When set to "StopHost": will cleanly stop the host, and log errors.
//
// In order for the Windows Service Management system to leverage configured
// recovery options, we need to terminate the process with a non-zero exit code.
Environment.Exit(1);
}
}
}
}