Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Guides building long-running .NET background services using BackgroundService, Generic Host, graceful shutdown, and health checks.
Use this skill ↓91% 95%+5 ptsof test cases passed
Passed 21 of 22 test cases with the skill, and 20 of 22 without it.
What interface structure should be defined for an asynchronous background task queue that supports queuing work items as delegates with scoped service provider access?
Defines methods for queuing work items taking Func<IServiceProvider, CancellationToken, ValueTask>.
3 of 3 safety checks passed
This reference covers BackgroundService patterns, graceful shutdown implementation, and health check patterns for .NET worker services.
The simplest pattern for periodic work:
public class BasicWorker : BackgroundService
{
private readonly ILogger<BasicWorker> _logger;
public BasicWorker(ILogger<BasicWorker> logger) => _logger = logger;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Processing at {Time}", DateTimeOffset.Now);
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
Create a new scope for each unit of work to properly handle scoped dependencies like DbContext:
public class ScopedDependencyWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<ScopedDependencyWorker> _logger;
public ScopedDependencyWorker(IServiceScopeFactory scopeFactory, ILogger<ScopedDependencyWorker> logger)
{
Next to this one in the catalogue, plus more from the same author.