.NET

Understanding .NET Worker Services: The Complete Guide

What .NET Worker Services are, when to use them, and three ways to schedule work: a continuous loop, a timer, and cron-style jobs.

Applications keep getting more complex, and sooner or later every one of them needs something reliable running in the background. In .NET that’s a Worker Service. This guide covers what they are, when to use them, how to schedule work in one, and how to deploy and look after it.

What are Worker Services?

A Worker Service is like a dedicated employee in your application who works in the background on specific tasks without interrupting the main application flow. It can run continuously, doing things like:

  • Processing queued items
  • Monitoring system resources
  • Scheduling routine maintenance
  • Handling file operations
  • Managing background calculations

Why use them?

Think of a restaurant. Your main application is the front-of-house staff, dealing directly with customers. The Worker Services are the kitchen staff, working behind the scenes, prepping ingredients, cleaning up, and handling all the tasks that keep the restaurant running.

What you get from that split is separation of concerns, a more responsive application, better resource management, room to scale, and simpler maintenance.

Getting started

Create a new Worker Service project, through Visual Studio or from the command line:

dotnet new worker -n MyFirstWorkerService

This creates a project with three files that matter.

  1. Program.cs, your service’s entry point:
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();
var host = builder.Build();
host.Run();
  1. Worker.cs, your service’s main logic:
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}
  1. appsettings.json, your configuration file:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Scheduling tasks

There are three common ways to schedule work in a Worker Service.

1. Continuous processing

This pattern runs tasks continuously in a loop:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        await ProcessWorkItem();
        await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
    }
}

2. Timer-based execution

For tasks that need to run at specific intervals:

private Timer? _timer;

public override Task StartAsync(CancellationToken cancellationToken)
{
    _timer = new Timer(DoWork, null, TimeSpan.Zero, 
        TimeSpan.FromHours(1));

    return base.StartAsync(cancellationToken);
}

private void DoWork(object? state)
{
    // Your hourly task here
}

3. Cron-style scheduling

For more complex schedules, use a library like Cronos:

private async Task ScheduleJob(CancellationToken cancellationToken)
{
    var cronExpression = "0 0 * * *"; // Run daily at midnight
    var parser = CronExpression.Parse(cronExpression);
    
    while (!cancellationToken.IsCancellationRequested)
    {
        var nextRun = parser.GetNextOccurrence(DateTime.UtcNow);
        await Task.Delay(nextRun.Value - DateTime.UtcNow, cancellationToken);
        await DoWork();
    }
}

Deployment options

  1. Windows Service
sc.exe create "MyWorkerService" binpath= "C:\Services\MyWorkerService.exe"
sc.exe start "MyWorkerService"
  1. Docker container
FROM mcr.microsoft.com/dotnet/runtime:8.0
COPY bin/Release/net8.0/publish/ App/
WORKDIR /App
ENTRYPOINT ["dotnet", "MyWorkerService.dll"]
  1. Azure hosted service

Deploy directly to Azure for cloud-based execution.

Best practices

  1. Error handling. Always handle errors, because a background service that dies quietly is worse than one that never ran:
try
{
    await ProcessWorkItem();
}
catch (Exception ex)
{
    _logger.LogError(ex, "Error processing work item");
    // Implement retry logic or fallback
}
  1. Configuration management. Use dependency injection and the configuration patterns:
public class Worker : BackgroundService
{
    private readonly IConfiguration _configuration;
    
    public Worker(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Resource management. Dispose of what you open:
public override async Task StopAsync(CancellationToken cancellationToken)
{
    _timer?.Dispose();
    await base.StopAsync(cancellationToken);
}
  1. Logging. Log enough that you can tell what happened afterwards:
_logger.LogInformation("Starting processing at: {time}", DateTimeOffset.Now);
_logger.LogError(ex, "Process failed with error");
_logger.LogWarning("Resource usage high: {usage}%", usage);

Common pitfalls

  1. Memory leaks. Use using statements, implement proper disposal patterns, and monitor memory usage.
  2. CPU utilization. Put real delays in your loops, use async/await correctly, and monitor performance.
  3. Deadlocks. Use async/await properly, implement timeouts, and handle cancellation correctly.

Monitoring and maintenance

  1. Health checks
public class HealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default)
    {
        // Implement health check logic
    }
}
  1. Performance monitoring
services.AddMetrics();

To sum up

Worker Services are a solid foundation for background processing in .NET. Start simple and add complexity only as you need it, handle your errors, pick the scheduling pattern that fits the job, and monitor and maintain the service once it’s running.


Looking for more? The File Watcher Service tutorial is the practical follow-up to this guide.


Have a .NET modernization project?

Free 30-minute call. No pitch, we just look at your migration together.

Get in touch