Open-Source .NET Programming • OSDotNet.008 • 35–45 minutes
A service that runs continuously must also know how to stop. The .NET Generic Host manages application lifetime, configuration, logging and registered hosted services. BackgroundService provides a structured way to run long-lived work and cooperate with shutdown instead of abruptly abandoning a task.
Prerequisites and objectives
Review dependency injection, configuration providers and SDK-style projects. Learners will register a hosted worker, pass a cancellation token into an asynchronous delay, and distinguish a graceful shutdown from an abrupt process termination.
Host lifetime and worker lifetime
Microsoft’s Worker Services guide describes StartAsync and StopAsync as hosted-service lifecycle methods. BackgroundService implements the interface and exposes ExecuteAsync, whose task represents the running worker. Register the class with AddHostedService and let the Generic Host coordinate startup and shutdown. The stopping token is a cooperative signal: the worker and its awaited operations must honor it.

Laboratory: a cancellable worker
On a machine with a supported .NET SDK and C# 12 or newer, run dotnet new worker -n WorkerLab, change into WorkerLab, and replace Program.cs with the code below. The unused template Worker.cs may remain or be removed. Run dotnet run, observe heartbeat messages, then press Ctrl+C to request graceful shutdown. This sample does not access the network, modify service configuration or process production data. Use the following Program.cs:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<ProbeWorker>();
using var host = builder.Build();
await host.RunAsync();
sealed class ProbeWorker(ILogger<ProbeWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
log.LogInformation(“Worker started”);
try
{
while (!stoppingToken.IsCancellationRequested)
{
log.LogInformation(“Heartbeat”);
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// Expected cooperative shutdown.
}
finally
{
log.LogInformation(“Worker cleanup”);
}
}
}
Expected behavior: the worker logs its start and heartbeat messages, then its cleanup message after cooperative cancellation. These are expected .NET results, not observed native compiler output. The token is passed into Task.Delay so shutdown need not wait for an uncancellable delay.
Testing the lifecycle concept
To demonstrate the expected cooperative lifecycle independently of the .NET runtime, execute the following Python reference model:
import asyncio
async def model(stop, ready, events):
events.append(‘started’)
ready.set()
try:
await stop.wait()
finally:
events.append(‘cleanup’)
async def main():
stop, ready = asyncio.Event(), asyncio.Event()
events = []
task = asyncio.create_task(model(stop, ready, events))
await ready.wait()
assert events == [‘started’]
assert not task.done()
stop.set()
await asyncio.wait_for(task, 1)
assert events == [‘started’, ‘cleanup’] and task.done()
print(‘3/3 reference-model assertions passed’)
asyncio.run(main())
Python 3.13.5 reran and passed all three assertions: the model started, stayed active before the stop signal and performed cleanup when signaled. This is a teaching analogue, not a test of .NET cancellation semantics or compilation. The .NET SDK was unavailable in the environment. A native run must still be completed before using this code in production.
Scoped dependencies and shutdown limits
Hosted services registered with AddHostedService are singletons. If each job uses a scoped dependency, create a scope for the work and dispose it rather than capturing a scoped service in the singleton. See Microsoft’s scoped BackgroundService example. Shutdown has a finite budget; a forced process termination may prevent cleanup. For durable jobs, use appropriate retry, persistence and idempotency mechanisms. A BackgroundService alone is not a durable scheduler.
Knowledge check
1. What triggers normal host shutdown? A host lifetime signal or an explicit StopApplication request. 2. Why pass the stopping token to awaited operations? To let supported operations end promptly. 3. Is cleanup guaranteed after forced termination? No. 4. Does the worker guarantee durable job execution? No. Review the CLR lesson for runtime context.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply