See the example code below. I would expect that the host automatically stops when the background service crashes, but this is not the case. The result is that the Windows service appears to be running but it doesn't perform any work... How can I make sure the Program detects that the background service has stopped?
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WorkerTest
{
public static class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private int _counter;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time} ({counter})", DateTimeOffset.Now, _counter++);
if (_counter > 10)
throw new Exception("Something happened!");
await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
}
}
finally
{
if (!stoppingToken.IsCancellationRequested)
_logger.LogError("Worker stopped unexpectedly");
}
}
}
}