Terminology

  • Background Service – the BackgroundService type.
  • Hosted Service – an implementation of IHostedService, or IHostedService itself.
  • Worker Service – the Worker Service template from dotnet new.

BackgroundService

  • An implementation of IHostedService.
  • Used for long-running, background processes.
  • Cross-platform. Can be used in place of a Windows Service.

Worker Service

dotnet new worker produces:
Program.cs:

using SomeNamespace;

// Create the default IHostBuilder:
IHost host = Host.CreateDefaultBuilder(args).ConfigureServices(services =>
{
    // Add the Worker class as a hosted service:
    services.AddHostedService<Worker>();
})
.Build(); // Build the IHost

await host.RunAsync(); // Run the app

Worker.cs:

namespace SomeNamespace;

public class Worker : BackgroundService 
{ // BackgroundService implements `IHostedService`.
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger) => _logger = logger;
    protected override async Task ExecuteAsync(CancellationToken stoppingToken) 
    {
        // Loop once per second and log the datetime:
        while (!stoppingToken.IsCancellationRequested) 
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

No Server Garbage Collection

Server GC is not enabled by default. To do so, add this to project file:

<PropertyGroup>
<ServerGarbageCollection>true</ServerGarbageCollection>
</PropertyGroup>

More info.

Worker Service with Containers

Visual Studio provides the option to opt into Docker support when creating a Worker service from the template. Doing so creates a Dockerfile and updates the project file accordingly.

IHostedService

Important: Worker services either derive from IHostedService or BackgroundService (which derives from IHostedService). When overriding IHostedService’s StartAsync or StopAsync methods, call and await the base class method to ensure proper startup/shutdown.