📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between a classic Windows Service and a .NET Worker Service? Explain how each is hosted, installed and logged, and how you would build a background service on .NET 10 that runs as a Windows service.

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).

Junior Theory Intermediate background-service generic-host legacy-migration windows-service worker-service

🎯 Key points

  • Classic: class derives from ServiceBase, overrides OnStart/OnStop, entry point ServiceBase.Run; installed with InstallUtil.exe, sc.exe or New-Service
  • Classic OnStart must return quickly (about 30 seconds by default) or the Service Control Manager fails the start; long work goes on a background thread
  • Worker Service: Generic Host (Host.CreateApplicationBuilder) plus BackgroundService.ExecuteAsync(CancellationToken), so start-up work runs asynchronously
  • AddWindowsService() (Microsoft.Extensions.Hosting.WindowsServices) integrates with the SCM; same app runs as a console
  • Install with sc.exe create or PowerShell New-Service; AddSystemd() for Linux; runs in containers unchanged
  • Logging: ILogger to Event Log on Windows, console/journald on Linux, Application Insights or OpenTelemetry anywhere
  • Graceful shutdown: honour the stopping token; HostOptions.ShutdownTimeout limits StopAsync; unhandled exceptions stop the host (StopHost) by default
  • Built-in DI and configuration (appsettings.json, env vars, Key Vault) instead of app.config; least-privilege service account

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, override OnStart and OnStop, and add a ProjectInstaller with ServiceProcessInstaller and ServiceInstaller so InstallUtil.exe can register it. OnStart has to return within about 30 seconds, so people start a thread or a Timer there. Logging usually goes to the Windows Event Log, and settings come from app.config.

On .NET 10 you'd build a Worker Service. It's the Generic Host, the same host ASP.NET Core uses, with a BackgroundService that does its work in ExecuteAsync until the cancellation token fires. You get DI, appsettings.json, ILogger and options for free. You call AddWindowsService() and the host reports start and stop to the SCM; you install it with sc.exe create or PowerShell New-Service. And the same binary runs from the command line for debugging, under systemd on Linux with AddSystemd(), 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."


Side by side

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows how classic services work and can build a correct, portable Worker Service on .NET 10.

Green flags

  • Explains ServiceBase, OnStart timeouts and InstallUtil
  • Knows BackgroundService, AddWindowsService() and sc.exe
  • Handles the stopping token and exceptions in ExecuteAsync
  • Mentions systemd or containers and least-privilege service accounts

Red flags

  • Thinks Worker Services can't run as Windows services
  • Ignores cancellation and error handling
  • Runs services as LocalSystem by default

📚 Learn in depth

1. How Windows runs services

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.

2. The Generic Host model

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.

3. Exceptions and shutdown

  • Since .NET 6, 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.

4. Installing

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.

Try it yourself

  1. dotnet new worker -n Invoice.Worker, add Microsoft.Extensions.Hosting.WindowsServices, call AddWindowsService(), publish and install with sc.exe create.
  2. Throw an exception inside ExecuteAsync and see the host stop; then set BackgroundServiceExceptionBehavior.Ignore and compare (and decide why StopHost is safer).
  3. Ignore the stopping token in a loop, stop the service, and watch the shutdown timeout expire.
  4. Run the same project in a container with docker run and check the logs on stdout.
  5. Add a health check endpoint or a heartbeat metric and alert when it stops.

💻 Code

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");
            }
        }
    }
}

⚠ Common mistakes

  • Mistake: Doing long work directly in 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.
  • Mistake: Ignoring the 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.
  • Mistake: Letting exceptions escape 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.
  • Mistake: Reading files relative to the current directory or hard-coding 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.
  • Mistake: Writing only to the Windows Event Log. Why it is wrong: It doesn't exist on Linux or in containers and is hard to search across servers. Instead: Log through ILogger to a central sink such as Application Insights or an OpenTelemetry collector.
  • Mistake: Keeping connection strings and API keys in 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.
  • Mistake: Running the service as LocalSystem. Why it is wrong: A compromise gets full machine rights. Instead: Use a virtual or group managed service account with least privilege.
  • Mistake: Using System.Timers.Timer with async work. Why it is wrong: Ticks can overlap and exceptions are swallowed. Instead: Use PeriodicTimer in an async loop.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the Generic Host Why: Checks they understand host start-up, lifetime events and graceful shutdown
    How to answer

    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.

  2. When: Candidate mentions exceptions stopping the host Why: Checks their global exception strategy including BackgroundService failures
    How to answer

    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.

↩ Usually asked after

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me