$npx -y skills add managedcode/dotnet-skills --skill worker-servicesBuild long-running .NET background services with BackgroundService, Generic Host, graceful shutdown, configuration, logging, and deployment patterns suited to workers and daemons. USE FOR: background services; scheduled workers; hosted services; worker extraction; graceful shut
| 1 | # .NET Worker Services |
| 2 | |
| 3 | ## Trigger On |
| 4 | |
| 5 | - building long-running background services or scheduled workers |
| 6 | - adding hosted services to an app or extracting them into a worker process |
| 7 | - reviewing graceful shutdown, cancellation, queue processing, or health behavior |
| 8 | |
| 9 | ## Documentation |
| 10 | |
| 11 | - [Worker Services in .NET](https://learn.microsoft.com/en-us/dotnet/core/extensions/workers) |
| 12 | - [Background tasks with hosted services in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0) |
| 13 | - [Create Windows Service using BackgroundService](https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service) |
| 14 | - [App health checks in .NET](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/diagnostic-health-checks) |
| 15 | - [Health checks in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-10.0) |
| 16 | |
| 17 | ### References |
| 18 | |
| 19 | - [patterns.md](references/patterns.md) - BackgroundService patterns, graceful shutdown, and health check implementations |
| 20 | - [anti-patterns.md](references/anti-patterns.md) - Common worker service mistakes and how to avoid them |
| 21 | |
| 22 | ## Workflow |
| 23 | |
| 24 | 1. **Use BackgroundService as your base class:** |
| 25 | - Provides standard `StartAsync`/`StopAsync` handling |
| 26 | - Focus on implementing `ExecuteAsync` only |
| 27 | - Proper cancellation token management built-in |
| 28 | |
| 29 | 2. **Handle scoped dependencies correctly:** |
| 30 | - Create service scopes for scoped services |
| 31 | - No scope is created by default in hosted services |
| 32 | |
| 33 | 3. **Implement graceful shutdown:** |
| 34 | - Propagate cancellation tokens throughout |
| 35 | - Complete work promptly when token fires |
| 36 | - Avoid ungraceful shutdown at timeout |
| 37 | |
| 38 | 4. **Keep execution loop thin:** |
| 39 | - Move business logic to testable services |
| 40 | - Handle exceptions to prevent service crashes |
| 41 | - Use `PeriodicTimer` for scheduled work |
| 42 | |
| 43 | 5. **Add observability:** |
| 44 | - Use health checks for readiness/liveness |
| 45 | - Expose metrics and structured logging |
| 46 | - Consider distributed locks for multi-instance |
| 47 | |
| 48 | ## Current Upstream Notes |
| 49 | |
| 50 | - `.NET runtime` `v10.0.10` is servicing. For workers, rerun cancellation, graceful shutdown, long-running GC/pinning, EventPipe diagnostics, NativeAOT, and platform-specific filesystem/drive checks after upgrading rather than changing architecture by default. |
| 51 | - Use the refreshed Worker Services and hosted-service Learn pages for exact current hosting and health-check APIs when adding new worker entry points. |
| 52 | |
| 53 | ## Basic BackgroundService Pattern |
| 54 | |
| 55 | ### Simple Worker |
| 56 | ```csharp |
| 57 | public class Worker : BackgroundService |
| 58 | { |
| 59 | private readonly ILogger<Worker> _logger; |
| 60 | |
| 61 | public Worker(ILogger<Worker> logger) |
| 62 | { |
| 63 | _logger = logger; |
| 64 | } |
| 65 | |
| 66 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 67 | { |
| 68 | _logger.LogInformation("Worker starting"); |
| 69 | |
| 70 | while (!stoppingToken.IsCancellationRequested) |
| 71 | { |
| 72 | try |
| 73 | { |
| 74 | _logger.LogInformation("Worker running at: {Time}", DateTimeOffset.Now); |
| 75 | await DoWorkAsync(stoppingToken); |
| 76 | await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); |
| 77 | } |
| 78 | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| 79 | { |
| 80 | // Graceful shutdown, not an error |
| 81 | break; |
| 82 | } |
| 83 | catch (Exception ex) |
| 84 | { |
| 85 | _logger.LogError(ex, "Error in worker iteration"); |
| 86 | // Continue or break based on error severity |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | _logger.LogInformation("Worker stopping"); |
| 91 | } |
| 92 | |
| 93 | private async Task DoWorkAsync(CancellationToken cancellationToken) |
| 94 | { |
| 95 | // Business logic here |
| 96 | } |
| 97 | } |
| 98 | ``` |
| 99 | |
| 100 | ### Using PeriodicTimer (Recommended) |
| 101 | ```csharp |
| 102 | public class TimedWorker : BackgroundService |
| 103 | { |
| 104 | private readonly ILogger<TimedWorker> _logger; |
| 105 | private readonly IServiceScopeFactory _scopeFactory; |
| 106 | private readonly TimeSpan _period = TimeSpan.FromMinutes(1); |
| 107 | |
| 108 | public TimedWorker(ILogger<TimedWorker> logger, IServiceScopeFactory scopeFactory) |
| 109 | { |
| 110 | _logger = logger; |
| 111 | _scopeFactory = scopeFactory; |
| 112 | } |
| 113 | |
| 114 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 115 | { |
| 116 | using var timer = new PeriodicTimer(_peri |