Covers ServiceBase-based Windows Services on .NET Framework (InstallUtil, OnStart/OnStop, Event Log) versus Worker Services on the Generic Host (BackgroundService, UseWindowsService, sc.exe, ILogger, systemd and containers).
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.
"A Windows Service is a long-running process that Windows starts and stops through the Service Control Manager, with no user logged in. On .NET Framework you write a class that inherits
ServiceBase, overrideOnStartandOnStop, and add aProjectInstallerwithServiceProcessInstallerandServiceInstallersoInstallUtil.execan register it.OnStarthas to return within about 30 seconds, so people start a thread or aTimerthere. Logging usually goes to the Windows Event Log, and settings come fromapp.config.On .NET 10 you'd build a Worker Service. It's the Generic Host, the same host ASP.NET Core uses, with a
BackgroundServicethat does its work inExecuteAsyncuntil the cancellation token fires. You get DI,appsettings.json,ILoggerand options for free. You callAddWindowsService()and the host reports start and stop to the SCM; you install it withsc.exe createor PowerShellNew-Service. And the same binary runs from the command line for debugging, under systemd on Linux withAddSystemd(), or in a container.The mistake I see is ignoring the stopping token or letting exceptions escape
ExecuteAsync. Since .NET 6 an unhandled exception there stops the whole host by default, and the service just dies. So I catch, log and decide whether to retry. The senior point: a Worker Service makes background work ordinary, testable code instead of a special Windows thing."
| Classic Windows Service (.NET Framework) | Worker Service (.NET 10) | |
|---|---|---|
| Base type | System.ServiceProcess.ServiceBase |
BackgroundService / IHostedService on the Generic Host |
| Entry | ServiceBase.Run(new MyService()) |
Host.CreateApplicationBuilder(args) |
| Start/stop | OnStart / OnStop |
ExecuteAsync(stoppingToken), StopAsync |
| Install | InstallUtil.exe + ProjectInstaller |
sc.exe create, New-Service, or an installer (MSI/WiX) |
| Config | app.config / ConfigurationManager |
appsettings.json, env vars, IOptions<T> |
| Logging | EventLog.WriteEntry |
ILogger → Event Log, console, OpenTelemetry |
| DI | None built in | Built in |
| Platforms | Windows only | Windows service, systemd, containers, console |
| Debugging | Attach to process | F5 as a console app |
A nightly invoice export service that used a System.Timers.Timer inside OnStart often swallowed exceptions on the timer thread, so failures were silent for days. Rebuilt as a Worker Service with PeriodicTimer, structured ILogger logs to Application Insights and a health check, failures surface as alerts within minutes, and the same image runs in Azure Container Apps in Australia East.
Checks that the candidate knows how classic services work and can build a correct, portable Worker Service on .NET 10.
Green flags
ServiceBase, OnStart timeouts and InstallUtilBackgroundService, AddWindowsService() and sc.exeExecuteAsyncRed flags
Service Control Manager (services.exe)
│ start request
▼
your.exe ── calls StartServiceCtrlDispatcher (ServiceBase.Run does this)
│ registers a control handler
│ SERVICE_START_PENDING → OnStart() → SERVICE_RUNNING
│ ... stop / shutdown control → OnStop() → SERVICE_STOPPED
If the process doesn't report RUNNING in time, the SCM marks the start as failed. Recovery options (restart on failure) are set per service with sc.exe failure.
Host.CreateApplicationBuilder builds configuration, logging and DI. Every registered IHostedService has StartAsync called in order at start and StopAsync in reverse order at shutdown. BackgroundService implements IHostedService and runs ExecuteAsync as a long-running task.
AddWindowsService() does three things when the process is started by the SCM: it sets the content root to the app folder (not C:\Windows\System32), switches the host lifetime to WindowsServiceLifetime so SCM stop requests trigger graceful shutdown, and adds an Event Log logger provider. When run from a console, it does nothing, so the same exe works in both places.
HostOptions.BackgroundServiceExceptionBehavior defaults to StopHost: an unhandled exception in ExecuteAsync logs and stops the application.HostOptions.ShutdownTimeout (30 seconds by default in current .NET) limits how long StopAsync can take. Work that ignores the token is abandoned.ExecuteAsync should await something quickly; a long synchronous loop at the start blocks other hosted services from starting.sc.exe create InvoiceExport binPath= "C:\apps\invoice\Invoice.Worker.exe" start= delayed-auto
sc.exe failure InvoiceExport reset= 86400 actions= restart/60000/restart/60000//
sc.exe start InvoiceExport
Run it under a least-privilege account (a virtual account like NT SERVICE\InvoiceExport or a group managed service account), not LocalSystem, in line with the ACSC Essential Eight's privilege restriction.
dotnet new worker -n Invoice.Worker, add Microsoft.Extensions.Hosting.WindowsServices, call AddWindowsService(), publish and install with sc.exe create.ExecuteAsync and see the host stop; then set BackgroundServiceExceptionBehavior.Ignore and compare (and decide why StopHost is safer).docker run and check the logs on stdout.A classic ServiceBase and the equivalent .NET 10 Worker Service.
// Before (.NET Framework 4.8): ServiceBase with a timer
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
public class InvoiceExportService : ServiceBase
{
private Timer _timer;
protected override void OnStart(string[] args)
{
_timer = new Timer(60_000);
_timer.Elapsed += (s, e) =>
{
// exceptions here are swallowed by System.Timers.Timer: silent failures
InvoiceExporter.ExportPending();
};
_timer.Start();
}
protected override void OnStop()
{
_timer?.Stop();
EventLog.WriteEntry("Invoice export stopped");
}
}
// After (.NET 10): Worker Service, Program.cs
using Invoice.Worker;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(o => o.ServiceName = "InvoiceExport"); // no-op when run as a console
builder.Services.AddSingleton<IInvoiceExporter, InvoiceExporter>();
builder.Services.AddHostedService<InvoiceExportWorker>();
builder.Build().Run();
// InvoiceExportWorker.cs
namespace Invoice.Worker;
public interface IInvoiceExporter
{
Task<int> ExportPendingAsync(CancellationToken ct);
}
public sealed class InvoiceExporter : IInvoiceExporter
{
public Task<int> ExportPendingAsync(CancellationToken ct) => Task.FromResult(0);
}
public sealed class InvoiceExportWorker(IInvoiceExporter exporter, ILogger<InvoiceExportWorker> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync(stoppingToken)) // ends cleanly on stop
{
try
{
var count = await exporter.ExportPendingAsync(stoppingToken);
logger.LogInformation("Exported {Count} invoices", count);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// catch per iteration so one bad run doesn't stop the host
logger.LogError(ex, "Invoice export failed");
}
}
}
}
OnStart of a classic service. Why it is wrong: The SCM times the start out and marks the service failed. Instead: Start background work and return, or use a Worker Service where ExecuteAsync runs in the background.stoppingToken. Why it is wrong: Stop requests hang until the shutdown timeout, then work is cut off mid-way. Instead: Pass the token to every async call and loop condition.ExecuteAsync. Why it is wrong: The default StopHost behaviour stops the whole service, on Windows and Linux alike; the SCM or systemd only restarts it if recovery is configured. Instead: Catch per unit of work, log, decide whether to retry, and configure sc.exe failure or Restart=on-failure.C:\ paths. Why it is wrong: Services start in C:\Windows\System32, and Windows paths break under systemd or in a container. Instead: Use AppContext.BaseDirectory, the host content root and Path.Combine, and put paths in configuration.ILogger to a central sink such as Application Insights or an OpenTelemetry collector.appsettings.json next to the exe. Why it is wrong: Anyone with file access to the server reads them. Instead: Use a managed identity with Key Vault, or DPAPI-protected secrets on-premises.LocalSystem. Why it is wrong: A compromise gets full machine rights. Instead: Use a virtual or group managed service account with least privilege.System.Timers.Timer with async work. Why it is wrong: Ticks can overlap and exceptions are swallowed. Instead: Use PeriodicTimer in an async loop.Moving a Windows Service to a Worker Service is usually one of the cheapest, highest-value steps in a .NET Framework migration: the hosting code is small, the business logic can often be reused, and the result runs anywhere. The real work is in what the old service quietly relied on: the machine's local file paths, Windows authentication to SQL Server, MSMQ, or registry settings.
| Hosting choice | When it fits | Cost | When not to |
|---|---|---|---|
| Worker as a Windows service | Must stay on existing Windows servers, uses Windows auth or local resources | Low | You want auto-scaling or no servers to patch |
| Worker in a container (AKS, Container Apps) | Cloud hosting, scale-out, Linux | Medium; externalise state and file access | Depends on Windows-only APIs |
| Azure Functions (timer or queue trigger) | Short, event-driven jobs | Low ops | Long-running loops, heavy in-memory state |
| Hangfire / Quartz.NET inside an app | Many scheduled jobs needing a dashboard and persistence | Medium | One simple loop |
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
Last updated 23 Nov 2026.