Create background services with IHostedService
✓Works with OpenClaudeYou are a .NET developer implementing long-running background tasks. The user wants to create and configure IHostedService implementations for background processing in .NET applications.
What to check first
- Verify your project targets .NET 6+ (or .NET Core 3.1+) by checking the
<TargetFramework>in your.csproj - Confirm Microsoft.Extensions.Hosting is installed via
dotnet add package Microsoft.Extensions.Hosting
Steps
- Create a class that implements
IHostedServicewithStartAsync()andStopAsync()methods - Use
BackgroundServiceabstract class as an alternative—it only requires implementingExecuteAsync(CancellationToken) - Inject
ILogger<T>into the constructor for logging lifecycle events - Implement graceful shutdown by respecting the
CancellationTokenpassed toExecuteAsync() - Use
Task.Delay()within awhile (!ct.IsCancellationRequested)loop for periodic tasks - Register the service in Program.cs using
services.AddHostedService<YourService>() - For worker services, ensure the host runs indefinitely with
host.RunAsync()orhost.Run() - Handle exceptions in
ExecuteAsync()with try-catch to prevent service crashes
Code
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// Implementation using BackgroundService base class
public class EmailQueueProcessor : BackgroundService
{
private readonly ILogger<EmailQueueProcessor> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly int _delayMilliseconds = 5000;
public EmailQueueProcessor(
ILogger<EmailQueueProcessor> logger,
IServiceProvider serviceProvider)
{
_logger = logger;
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("EmailQueueProcessor started at {time}", DateTimeOffset.Now);
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Create a scope for each iteration to resolve scoped services
using (var scope = _serviceProvider.CreateScope())
{
var emailService = scope.ServiceProvider.GetRequiredService<IEmailService>();
await emailService.ProcessQueueAsync(stoppingToken);
}
await Task.Delay(_delayMilliseconds, stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation("EmailQueueProcessor cancellation requested");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing email queue");
// Continue running despite errors
await Task.Delay(_delayMilliseconds,
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related .NET / C# Skills
Other Claude Code skills in the same category — free to download.
ASP.NET Core API
Scaffold ASP.NET Core Web API with controllers and middleware
Entity Framework Core
Set up Entity Framework Core with migrations and queries
ASP.NET Auth
Configure ASP.NET Identity with JWT and cookie authentication
Minimal API
Build minimal APIs with endpoint mapping
Blazor
Create Blazor components for interactive web UI
.NET Testing
Write xUnit tests with Moq and FluentAssertions
SignalR
Implement real-time communication with SignalR
Want a .NET / C# skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.