wshaddix/dotnet-skills/background-services

Claude Code and agent skill by wshaddix/dotnet-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Hosted services, background jobs, outbox patterns, and graceful shutdown handling for ASP.NET Core applications. Includes patterns for reliable job processing, distributed systems, and lifecycle management. Use when implementing background processing in ASP.NET Core applications, handling outbox patterns for reliable message delivery, or managing graceful service shutdown.

Install

npx vskill@latest install wshaddix/dotnet-skills/background-services

SKILL.md

Background Services in ASP.NET Core

Rationale

Background services are essential for offloading work from the request pipeline, processing queues, and handling scheduled tasks. Poorly implemented background services can lead to data loss, orphaned jobs, and resource leaks. These patterns ensure reliable, observable, and gracefully degrading background processing in production applications.


BackgroundService vs IHostedService

FeatureBackgroundServiceIHostedService
PurposeLong-running loop or continuous workStartup/shutdown hooks
MethodsOverride ExecuteAsyncImplement StartAsync + StopAsync
LifetimeRuns until cancellation or host shutdownStartAsync runs at startup, StopAsync at shutdown
Use whenPolling queues, processing streams, periodic jobsDatabase migrations, cache warming, resource cleanup

Pattern 1: Basic BackgroundService Structure

Use BackgroundService base class for consistent lifecycle management and cancellation support.

csharp
public sealed class OrderProcessorWorker(
IServiceScopeFactory scopeFactory,
ILogger<OrderProcessorWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Order processor started");
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
var processor = scope.ServiceProvider
.GetRequiredService<IOrderProcessor>();
var processed = await processor.ProcessPendingAsync(stoppingToken);
if (processed == 0)
{
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "Error processing orders");
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
logger.LogInformation("Order processor stopped");
}
}
// Registration
builder.Services.AddHostedService<OrderProcessorWorker>();
Critical Rules for BackgroundService
  1. Always create scopes -- BackgroundService is registered as a singleton. Inject IServiceScopeFactory, not scoped services directly.
  2. Always handle exceptions -- by default, unhandled exceptions in ExecuteAsync stop the host. Wrap the loop body in try/catch.
  3. Always respect the stopping token -- check stoppingToken.IsCancellationRequested and pass the token to all async calls.
  4. Back off on empty/error -- avoid tight polling loops that waste CPU. Use Task.Delay with the stopping token.

Pattern 2: IHostedService for Startup/Shutdown Hooks

Startup Hook (Cache Warming, Migrations)
csharp
public sealed class CacheWarmupService(
IServiceScopeFactory scopeFactory,
ILogger<CacheWarmupService> logger) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Warming caches");
using var scope = scopeFactory.CreateScope();
var cache = scope.ServiceProvider.GetRequiredService<IProductCache>();
await cache.WarmAsync(cancellationToken);
logger.LogInformation("Cache warmup complete");
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
Startup + Shutdown (Resource Lifecycle)
csharp
public sealed class MessageBusService(
ILogger<MessageBusService> logger) : IHostedService
{
private IConnection? _connection;
public async Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Connecting to message bus");
_connection = await CreateConnectionAsync(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Disconnecting from message bus");
if (_connection is not null)
{
await _connection.CloseAsync(cancellationToken);
_connection = null;
}
}
private static Task<IConnection> CreateConnectionAsync(CancellationToken ct) =>
throw new NotImplementedException();
}

Pattern 3: Hosted Service Lifecycle

Startup Sequence
  1. IHostedService.StartAsync is called for each registered service in registration order
  2. BackgroundService.ExecuteAsync is called after StartAsync completes (it runs concurrently -- the host does not wait for it to finish)
  3. The host is ready to serve requests after all StartAsync calls complete

Important: ExecuteAsync must not block before yielding to the caller. The first await in ExecuteAsync is where control returns to the host.

csharp
public sealed class MyWorker : BackgroundService
{
public override async Task StartAsync(CancellationToken cancellationToken)
{
await InitializeAsync(cancellationToken);
await base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await DoWorkAsync(stoppingToken);
}
}
}
Shutdown Sequence
  1. IHostApplicationLifetime.ApplicationStopping is triggered
  2. The host calls StopAsync on each hosted service in reverse registration order
  3. For BackgroundService, the stopping token is cancelled, then StopAsync waits for ExecuteAsync to complete
  4. IHostApplicationLifetime.ApplicationStopped is triggered

Pattern 4: Outbox Pattern for Reliable Messaging

Ensure messages are never lost by storing them in the database transactionally before async processing.

csharp
public class OutboxMessage
{
public Guid Id { get; set; }
public required string Type { get; set; }
public required string Payload { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? ProcessedAt { get; set; }
public string? Error { get; set; }
public int RetryCount { get; set; }
}
public interface IOutboxRepository
{
Task AddAsync(OutboxMessage message, CancellationToken ct = default);
Task<IReadOnlyList<OutboxMessage>> GetPendingAsync(int batchSize, CancellationToken ct = default);
Task MarkProcessedAsync(Guid messageId, CancellationToken ct = default);
Task MarkFailedAsync(Guid messageId, string error, CancellationToken ct = default);
}
public class OrderService
{
private readonly ApplicationDbContext _db;
private readonly IOutboxRepository _outbox;
public async Task<Order> CreateOrderAsync(CreateOrderRequest request)
{
await using var transaction = await _db.Database.BeginTransactionAsync();
try
{
var order = new Order { };
_db.Orders.Add(order);
var message = new OutboxMessage
{
Id = Guid.NewGuid(),
Type = nameof(OrderCreatedEvent),
Payload = JsonSerializer.Serialize(new OrderCreatedEvent
{
OrderId = order.Id,
CustomerEmail = request.CustomerEmail
}),
CreatedAt = DateTimeOffset.UtcNow
};
await _outbox.AddAsync(message);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
return order;
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
}
public class OutboxProcessor : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<OutboxProcessor> _logger;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var scope = _serviceProvider.CreateAsyncScope();
var outbox = scope.ServiceProvider.GetRequiredService<IOutboxRepository>();
var publisher = scope.ServiceProvider.GetRequiredService<IEventPublisher>();
var messages = await outbox.GetPendingAsync(batchSize: 10, stoppingToken);
foreach (var message in messages)
{
try
{
await publisher.PublishAsync(message.Type, message.Payload, stoppingToken);
await outbox.MarkProcessedAsync(message.Id, stoppingToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process outbox message {MessageId}", message.Id);
await outbox.MarkFailedAsync(message.Id, ex.Message, stoppingToken);
}
}
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in outbox processor");
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
}

Pattern 5: Graceful Shutdown Handling

Implement IHostedLifecycleService for fine-grained control over startup and shutdown sequences.

csharp
public class GracefulWorker : BackgroundService
{
private readonly IHostApplicationLifetime _lifetime;
private readonly ILogger<GracefulWorker> _logger;
private readonly Channel<WorkItem> _workChannel;
public GracefulWorker(
IHostApplicationLifetime lifetime,
ILogger<GracefulWorker> logger)
{
_lifetime = lifetime;
_logger = logger;
_workChannel = Channel.CreateUnbounded<WorkItem>();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_lifetime.ApplicationStopping.Register(() =>
{
_logger.LogInformation("Shutdown requested, draining work channel...");
});
await foreach (var workItem in _workChannel.Reader.ReadAllAsync(stoppingToken))
{
try
{
await ProcessWorkItemAsync(workItem, stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogWarning("Work item {WorkId} cancelled due to shutdown", workItem.Id);
throw;
}
}
}
private async Task ProcessWorkItemAsync(WorkItem item, CancellationToken ct)
{
using var activity = new Activity("ProcessWorkItem").Start();
_logger.LogInformation("Processing work item {WorkId}", item.Id);
await Task.Delay(item.Duration, ct);
_logger.LogInformation("Completed work item {WorkId}", item.Id);
}
}
public class LifecycleAwareService : IHostedLifecycleService
{
private readonly ILogger<LifecycleAwareService> _logger;
public LifecycleAwareService(ILogger<LifecycleAwareService> logger) => _logger = logger;
public Task StartingAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service starting...");
return Task.CompletedTask;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service start called");
return Task.CompletedTask;
}
public Task StartedAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service started successfully");
return Task.CompletedTask;
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
86
Repository forks
14
7-day trend score
3

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 18 Mar 2026, 7 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/wshaddix/dotnet-skills/background-services/badge)](https://verified-skill.com/skills/wshaddix/dotnet-skills/background-services)

Something wrong with this skill or its page? Tell us.