Hands-on migration of a ServiceBase Windows Service to a .NET 10 Worker Service: BackgroundService with PeriodicTimer, AddWindowsService, graceful shutdown and HostOptions, scoped services via IServiceScopeFactory, EventLog vs console logging, sc.exe installation, and a container image for Linux.
The service logic moves into a BackgroundService on the Generic Host. OnStart/OnStop become ExecuteAsync and the stopping token; System.Timers.Timer becomes a PeriodicTimer loop, which never overlaps ticks. AddWindowsService() wires the host to the Windows Service Control Manager when it runs as a service, and does nothing otherwise, so the same binary runs under sc.exe on the old server and in a Linux container.
Configuration moves to appsettings.json plus environment variables; logging goes to the EventLog on Windows and console/JSON in containers. Scoped dependencies like DbContext need a scope per unit of work via IServiceScopeFactory. The trade-off: the Generic Host adds a little start-up weight, but you gain DI, config, logging and graceful shutdown that the old ServiceBase code did by hand.
"The old pattern is a class that inherits
ServiceBase, starts aSystem.Timers.TimerinOnStart, does the work in theElapsedhandler and stops the timer inOnStop, installed withinstallutil. It works, but it has classic bugs: ticks overlap when a run takes longer than the interval, exceptions inElapsedare swallowed, andOnStopdoesn't wait for the current run to finish.On .NET 10 I move the logic into a
BackgroundServicehosted by the Generic Host.ExecuteAsyncruns aPeriodicTimerloop:while (await timer.WaitForNextTickAsync(stoppingToken)). That gives me no overlapping runs and clean cancellation. I callAddWindowsService()on the builder, which hooks the host lifetime into the Service Control Manager when it's running as a Windows service and is a no-op otherwise, so the same build runs on the existing Windows server and in a Linux container. Because a hosted service is a singleton, anything scoped, like aDbContext, comes from a fresh scope per run viaIServiceScopeFactory. Configuration moves fromapp.configtoappsettings.jsonplus environment variables, and logging goes to the EventLog provider on Windows and JSON console output in containers.The mistake I see is forgetting shutdown. Docker sends SIGTERM and gives you 10 seconds by default; the host's default shutdown timeout is 30 seconds. If the work loop ignores the token, the run is killed half-way. I pass the token everywhere and set both timeouts deliberately."
| .NET Framework Windows Service | .NET 10 Worker Service |
|---|---|
ServiceBase.OnStart / OnStop |
BackgroundService.ExecuteAsync(stoppingToken) |
System.Timers.Timer + Elapsed |
PeriodicTimer.WaitForNextTickAsync |
app.config <appSettings> |
appsettings.json, env vars, Key Vault, IOptions<T> |
EventLog.WriteEntry |
ILogger + EventLog provider (Windows) / console JSON |
installutil + ProjectInstaller |
sc.exe create / New-Service, or a container |
new SqlConnection per tick |
Scoped DbContext per run via IServiceScopeFactory |
| Swallowed exceptions | Host stops by default (BackgroundServiceExceptionBehavior.StopHost) |
| Host | When it fits | Watch out for |
|---|---|---|
| Windows service on the existing VM | Fast first step, Windows dependencies | Recovery options, service account rights |
| Linux container (AKS, Container Apps) | Portable, scales, standard ops | SIGTERM handling, no EventLog, file paths |
| Azure Container Apps jobs / Functions timer | Scheduled work with no always-on process | Cold start, execution limits |
A nightly invoice-export service moved from ServiceBase to a Worker Service. The first month on the old server it stopped double-processing (overlapping timer ticks had caused about 1 in 200 invoices to be exported twice). It later moved unchanged to Azure Container Apps, with shutdown completing within 8 seconds of a deployment.
Checks whether the candidate can actually write a correct modern background service and avoid the classic timer, scope and shutdown bugs.
Green flags
BackgroundService with PeriodicTimer and the stopping tokenAddWindowsService() is a no-op outside the SCMDbContextRed flags
System.Timers.Timer and async void handlersThe Service Control Manager (SCM) starts the process and calls into ServiceBase via ServiceBase.Run. OnStart must return quickly (about 30 seconds by default) or the SCM reports a start failure, which is why legacy services kick off a timer or thread and return.
SCM --start--> service.exe --ServiceBase.Run--> OnStart() -> Timer.Start()
Timer.Elapsed (thread-pool thread) -> DoWork()
SCM --stop---> OnStop() -> Timer.Stop() (current DoWork keeps running or is killed)
Host.CreateApplicationBuilder sets up configuration, DI, logging and an IHostLifetime. AddWindowsService() swaps the lifetime for WindowsServiceLifetime, which talks to the SCM, and sets the content root to AppContext.BaseDirectory (a service's working directory is C:\Windows\System32). When not running as a service, it does nothing, so you can debug with F5.
Host.StartAsync
-> IHostedService.StartAsync for each hosted service
BackgroundService.StartAsync -> runs ExecuteAsync (returns at first await)
SIGTERM / SCM stop / Ctrl+C
-> IHostApplicationLifetime.ApplicationStopping
-> stoppingToken cancelled
-> host waits up to HostOptions.ShutdownTimeout (30 s default)
System.Timers.Timer raises Elapsed on the thread pool every interval regardless of whether the previous handler finished, so slow runs overlap. PeriodicTimer (since .NET 6) is awaited: the next tick is only observed after the loop body finishes, and missed ticks coalesce into one. It also takes the cancellation token directly.
Hosted services are registered as singletons. Injecting a scoped DbContext into the constructor either fails validation or (worse, without validation) keeps one context alive forever, growing its change tracker. Create a scope per unit of work:
loop tick -> using scope = scopeFactory.CreateAsyncScope()
-> resolve DbContext, repositories
-> do work, SaveChangesAsync
-> scope disposed (context disposed)
Since .NET 6, an unhandled exception from ExecuteAsync stops the host (BackgroundServiceExceptionBehavior.StopHost) and logs it. On Windows, configure SCM recovery (sc.exe failure) to restart; in containers, the orchestrator restarts the pod. Catch and log per-iteration exceptions you can recover from so one bad record doesn't stop the service.
Docker sends SIGTERM, then SIGKILL after the grace period (10 s default in Docker, 30 s in Kubernetes). The .NET host handles SIGTERM via ConsoleLifetime. Make HostOptions.ShutdownTimeout shorter than the orchestrator's grace period, so the host finishes cleanly before being killed. Use the mcr.microsoft.com/dotnet/runtime:10.0 image (no ASP.NET needed) and run as the non-root app user.
dotnet new worker -n InvoiceExporter, add Microsoft.Extensions.Hosting.WindowsServices, call AddWindowsService(), and install it with sc.exe create.System.Timers.Timer and then with PeriodicTimer; log the overlap.docker stop it, and watch whether your 'run completed' log line appears; adjust ShutdownTimeout.DbContext directly into the worker with ValidateScopes on and read the error; then fix it with IServiceScopeFactory.ExecuteAsync and observe the host stop; configure sc.exe failure to restart it.Before: the legacy service with overlapping ticks and swallowed errors.
// BEFORE: .NET Framework 4.8 Windows Service
public partial class InvoiceExportService : ServiceBase
{
private readonly System.Timers.Timer _timer = new(TimeSpan.FromMinutes(5).TotalMilliseconds);
protected override void OnStart(string[] args)
{
_timer.Elapsed += (_, _) => ExportInvoices(); // overlaps if a run takes > 5 min
_timer.Start();
}
protected override void OnStop() => _timer.Stop(); // doesn't wait for the current run
private void ExportInvoices()
{
try
{
var cs = ConfigurationManager.ConnectionStrings["Billing"].ConnectionString;
using var conn = new SqlConnection(cs);
// ... export
}
catch (Exception ex)
{
EventLog.WriteEntry("InvoiceExport", ex.ToString(), EventLogEntryType.Error);
}
}
}
After: one Worker Service binary for a Windows service and a Linux container.
// Program.cs (.NET 10)
using InvoiceExporter;
using Microsoft.EntityFrameworkCore;
var builder = Host.CreateApplicationBuilder(args);
// Talks to the SCM when running as a Windows service; no-op in a container or under F5
builder.Services.AddWindowsService(o => o.ServiceName = "Contoso Invoice Export");
builder.Services.AddOptions<ExportOptions>()
.Bind(builder.Configuration.GetSection("Export"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddDbContext<BillingDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Billing")));
builder.Services.AddScoped<IInvoiceExporter, InvoiceExporterService>();
builder.Services.AddHostedService<InvoiceExportWorker>();
// Finish before Docker/Kubernetes sends SIGKILL
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(20));
builder.Build().Run();
// InvoiceExportWorker.cs
namespace InvoiceExporter;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;
public sealed record ExportOptions
{
[Range(1, 1440)] public int IntervalMinutes { get; init; } = 5;
}
public sealed partial class InvoiceExportWorker(
IServiceScopeFactory scopeFactory,
IOptions<ExportOptions> options,
ILogger<InvoiceExportWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(options.Value.IntervalMinutes));
// Awaited ticks: a slow run delays the next one instead of overlapping it
do
{
try
{
// Hosted services are singletons; DbContext is scoped, so one scope per run
await using var scope = scopeFactory.CreateAsyncScope();
var exporter = scope.ServiceProvider.GetRequiredService<IInvoiceExporter>();
var count = await exporter.ExportPendingAsync(stoppingToken);
LogExported(count);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break; // shutting down
}
catch (Exception ex)
{
// One failed run shouldn't stop the service; log and wait for the next tick
LogRunFailed(ex);
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
[LoggerMessage(Level = LogLevel.Information, Message = "Exported {Count} invoices")]
private partial void LogExported(int count);
[LoggerMessage(Level = LogLevel.Error, Message = "Invoice export run failed")]
private partial void LogRunFailed(Exception ex);
}
public interface IInvoiceExporter { Task<int> ExportPendingAsync(CancellationToken ct); }
Installing on Windows and building the container:
# Windows (elevated PowerShell): replaces installutil
sc.exe create "Contoso Invoice Export" binPath= "C:\Services\InvoiceExporter\InvoiceExporter.exe" start= auto
sc.exe failure "Contoso Invoice Export" reset= 86400 actions= restart/60000/restart/60000/none/0
# Linux container image without a Dockerfile (SDK container support)
dotnet publish -c Release -r linux-x64 /t:PublishContainer \
-p:ContainerBaseImage=mcr.microsoft.com/dotnet/runtime:10.0
System.Timers.Timer as-is. Why it is wrong: ticks overlap when a run is slow, causing double processing. Instead: use a PeriodicTimer loop awaited inside ExecuteAsync.DbContext into the hosted service constructor. Why it is wrong: the worker is a singleton, so the context lives forever (captive dependency) or fails scope validation. Instead: create a scope per run with IServiceScopeFactory.stoppingToken to every async call and set ShutdownTimeout below the orchestrator's grace period.app.config into appsettings.json or baking them into the image. Why it is wrong: secrets end up in git and in every image layer anyone can pull. Instead: use Key Vault with managed identity (or Kubernetes secrets / Container Apps secrets) and environment variables; on the Windows server, use a gMSA with Windows authentication to SQL Server.C:\Windows\System32. Instead: AddWindowsService() sets the content root; use IHostEnvironment.ContentRootPath or absolute config paths.PlatformNotSupportedException on Linux. Instead: log through ILogger and pick providers per environment.The big win isn't the new API, it's that one binary runs in both places, so you can separate the runtime migration from the hosting migration. Move to .NET 10 on the same server first (low risk, same network, same service account), then move hosting to containers once it has run cleanly for a while.
Also ask whether it should be a long-running process at all. A job that runs every five minutes is often better as an Azure Container Apps job or a Functions timer trigger, which removes the always-on cost and the restart logic. Long-running is right when work arrives continuously (queue consumers) or start-up is expensive.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Worker Service as Windows service | First step, Windows-only dependencies | Still a VM to patch | You want to retire the server |
| Worker Service in a container | Portable, standard ops, scale-out | Image pipeline, SIGTERM handling | Needs registry, COM or EventLog |
| Container Apps job / Functions timer | Scheduled, short work | Cold starts, execution limits | Continuous queue processing |
| Keep the old service | Retiring within months | Skills and patching risk | Active development |
A classic Windows Service on .NET Framework is a class that derives from ServiceBase and overrides OnStart and OnStop. You install it with InstallUtil.exe and a ProjectInstaller, configure it with app.config, and log with EventLog.WriteEntry. It only runs on Windows, and debugging means attaching to a running service.
A Worker Service on modern .NET is a console app on the Generic Host: a BackgroundService with ExecuteAsync(CancellationToken), built-in DI, configuration and ILogger. Add AddWindowsService() and it talks to the Service Control Manager; install with sc.exe create. The same code runs as a console app, a Linux systemd service or in a container. The trade-off: you get portability and testability, but you must handle the stopping token and exceptions yourself.
IHttpContextAccessor stores the current context in an AsyncLocal, so it flows with the request's async calls and is valid only while the request runs. Fire-and-forget work, Task.Run that outlives the request, or a singleton reading it later can see null or a recycled context from another request, because HttpContext objects are pooled. HttpContext is also not thread-safe: reading or writing it from parallel tasks, even during the request, can race and corrupt state. Don't capture scoped services (like a DbContext) either; they are disposed when the request scope ends. Instead, copy the values you need (user ID, correlation ID, tenant) into a message or parameters before starting the work, create a new DI scope in the background worker, and use a queue (Channel<T> with a BackgroundService) for anything that must outlive the request.
Kubernetes removes the pod from Service endpoints and sends SIGTERM, waits terminationGracePeriodSeconds (30 s default), then sends SIGKILL. The .NET host cancels the stopping token and waits up to HostOptions.ShutdownTimeout for hosted services to finish.
Size the timeouts from your work: ShutdownTimeout must cover the longest unit of work (or the time to checkpoint it), and the pod's grace period must be longer than ShutdownTimeout plus any preStop delay, otherwise SIGKILL arrives first. Stop taking new work (stop pulling from the queue), finish or checkpoint the current item, and make processing idempotent so a killed item is safely retried. A preStop hook (e.g. sleep 5) delays SIGTERM so load balancers stop routing to the pod first; that matters for HTTP workloads more than queue workers. Log shutdown start, items abandoned and duration so lost work is visible.
How to tell it (STAR)
**S:** We had [a billing Windows Service] exporting invoices every five minutes. **T:** After a slow database night customers were charged twice, and I was asked to find out why and stop it happening again. **A:** I lined up export times against the timer interval and saw overlapping runs picking the same rows, a known behaviour of `System.Timers.Timer`. We blocked duplicates with a unique key the same day, then I migrated the service to a .NET 10 Worker Service with a `PeriodicTimer`, atomic row claiming and an idempotency key. **R:** Duplicates went from [about 70 that night] to zero over [the following six months], and the same binary later moved to containers without changes.
Last updated 23 Nov 2026.