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

📚 Interview question

Show me how you would migrate a classic .NET Framework Windows Service (a ServiceBase class with a Timer and installutil) to a .NET 10 Worker Service that runs as a Windows service on the existing server and also in a Linux container. How do you handle start-up and shutdown, configuration, logging, scoped dependencies and installation?

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.

Mid-Level Coding Intermediate background-service containers generic-host legacy-migration windows-service worker-service

🎯 Key points

  • ServiceBase OnStart/OnStop become a BackgroundService ExecuteAsync loop on the Generic Host
  • AddWindowsService() (Microsoft.Extensions.Hosting.WindowsServices) is a no-op when not running as a service, so one binary runs everywhere
  • PeriodicTimer + CancellationToken replace System.Timers.Timer: no overlapping ticks, clean cancellation
  • Graceful shutdown: stoppingToken, HostOptions.ShutdownTimeout below the Docker/Kubernetes grace period
  • Create a scope per unit of work with IServiceScopeFactory for DbContext and other scoped services
  • Keep the worker stateless (state in the database or queue, idempotent work) so it can restart, move and scale out
  • Secrets from Key Vault with managed identity (or Kubernetes secrets), not app.config or the image; logs via EventLog on Windows, JSON console + OpenTelemetry in containers
  • Install with sc.exe create (not installutil), set recovery; unhandled exceptions stop the host by default since .NET 6

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The old pattern is a class that inherits ServiceBase, starts a System.Timers.Timer in OnStart, does the work in the Elapsed handler and stops the timer in OnStop, installed with installutil. It works, but it has classic bugs: ticks overlap when a run takes longer than the interval, exceptions in Elapsed are swallowed, and OnStop doesn't wait for the current run to finish.

On .NET 10 I move the logic into a BackgroundService hosted by the Generic Host. ExecuteAsync runs a PeriodicTimer loop: while (await timer.WaitForNextTickAsync(stoppingToken)). That gives me no overlapping runs and clean cancellation. I call AddWindowsService() 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 a DbContext, comes from a fresh scope per run via IServiceScopeFactory. Configuration moves from app.config to appsettings.json plus 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."


Legacy to modern mapping

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

Hosting choices

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can actually write a correct modern background service and avoid the classic timer, scope and shutdown bugs.

Green flags

  • Uses BackgroundService with PeriodicTimer and the stopping token
  • Knows AddWindowsService() is a no-op outside the SCM
  • Creates a scope per run for DbContext
  • Handles SIGTERM, shutdown timeout and per-iteration exceptions

Red flags

  • Keeps System.Timers.Timer and async void handlers
  • Injects scoped services into a singleton worker
  • No plan for logging or installation without installutil

📚 Learn in depth

1. How a classic Windows Service works

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

2. How the Generic Host replaces it

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)

3. PeriodicTimer vs System.Timers.Timer

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.

4. Scopes in a singleton

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)

5. Exceptions

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.

6. Containers

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.

Try it yourself

  1. dotnet new worker -n InvoiceExporter, add Microsoft.Extensions.Hosting.WindowsServices, call AddWindowsService(), and install it with sc.exe create.
  2. Make one iteration take longer than the interval with System.Timers.Timer and then with PeriodicTimer; log the overlap.
  3. Run it in Docker, docker stop it, and watch whether your 'run completed' log line appears; adjust ShutdownTimeout.
  4. Inject a DbContext directly into the worker with ValidateScopes on and read the error; then fix it with IServiceScopeFactory.
  5. Throw from ExecuteAsync and observe the host stop; configure sc.exe failure to restart it.

💻 Code

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

⚠ Common mistakes

  • Mistake: Porting the 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.
  • Mistake: Injecting 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.
  • Mistake: Ignoring the stopping token. Why it is wrong: SIGTERM or an SCM stop kills the run half-way after the timeout. Instead: pass stoppingToken to every async call and set ShutdownTimeout below the orchestrator's grace period.
  • Mistake: Keeping state in memory between runs (a static 'last processed id', an in-memory queue). Why it is wrong: a restart, a redeploy or a second replica loses or duplicates work. Instead: keep progress in the database or the queue, claim work atomically and make processing idempotent.
  • Mistake: Copying connection strings from 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.
  • Mistake: Relying on the working directory for relative paths. Why it is wrong: a Windows service starts in C:\Windows\System32. Instead: AddWindowsService() sets the content root; use IHostEnvironment.ContentRootPath or absolute config paths.
  • Mistake: Catching nothing in the loop. Why it is wrong: since .NET 6, an unhandled exception stops the whole host. Instead: catch per iteration, log, and let the loop continue; configure restart for truly fatal errors.
  • Mistake: Writing to the EventLog directly in shared code. Why it is wrong: it throws PlatformNotSupportedException on Linux. Instead: log through ILogger and pick providers per environment.
  • Mistake: Running the service as LocalSystem. Why it is wrong: excessive privilege (an Essential Eight concern). Instead: use a virtual or group-managed service account with only the rights it needs.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is unclear on how a Windows Service and a Worker Service differ conceptually Why: Checks the fundamentals of hosting, installation and logging
    How to 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.

  2. When: Candidate mentions using IHttpContextAccessor or request state in background work Why: Checks they know background work has no request context and what to pass instead
    How to answer

    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.

  3. When: Candidate mentions SIGTERM or ShutdownTimeout Why: Checks practical knowledge of host shutdown and orchestrator grace periods
    How to answer

    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.

🛠 Real-world problems: how you handle them

Invoice export double-processes after a slow database night
Situation
A [billing] Windows Service on .NET Framework 4.8 exports invoices to [a payment provider] every 5 minutes. [About 15,000] invoices a day.
Signals
Customers in [Australia] reported duplicate charges; the provider's reconciliation showed [about 70] duplicate exports on one night. EventLog had no errors. SQL Server waits were high during an index rebuild that night.
Investigation
Correlated export timestamps with the timer interval: runs that took over 5 minutes overlapped, and both selected the same 'pending' rows. Reproduced locally by adding a delay. Confirmed `System.Timers.Timer` fires regardless of the previous handler.
Resolution
Immediate: refunded duplicates and added a unique key on the export record to block double sends. Real fix: migrated to a .NET 10 Worker Service with a `PeriodicTimer` loop, a scope per run, and rows claimed with an `UPDATE ... OUTPUT` so a row can only be picked once.
Prevention
Integration test that runs two iterations concurrently and asserts no duplicates; idempotency key sent to the provider; alert on run duration over 80% of the interval.

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.

More in Migration Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me