$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
.NET / C#intermediateNew

.NET Background Services

Share

Create background services with IHostedService

Works with OpenClaude

You 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

  1. Create a class that implements IHostedService with StartAsync() and StopAsync() methods
  2. Use BackgroundService abstract class as an alternative—it only requires implementing ExecuteAsync(CancellationToken)
  3. Inject ILogger<T> into the constructor for logging lifecycle events
  4. Implement graceful shutdown by respecting the CancellationToken passed to ExecuteAsync()
  5. Use Task.Delay() within a while (!ct.IsCancellationRequested) loop for periodic tasks
  6. Register the service in Program.cs using services.AddHostedService<YourService>()
  7. For worker services, ensure the host runs indefinitely with host.RunAsync() or host.Run()
  8. 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

Quick Info

Category.NET / C#
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
dotnetbackground-serviceshosted-service

Install command:

curl -o ~/.claude/skills/dotnet-background.md https://clskills.in/skills/dotnet/dotnet-background.md

Related .NET / C# Skills

Other Claude Code skills in the same category — free to download.

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.