Recipe 14.1 · C#
Replacing the Thread.Sleep Loop With BackgroundService
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
A Windows Service runs a sync every five minutes. Stopping it takes minutes or fails with "the service did not respond to the stop request in a timely fashion". An exception in the sync is swallowed or, worse, ends the thread so the service shows as running while doing nothing. Nothing in the job can be unit tested, because the database connection and the schedule are mixed in one class.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: unstoppable sleep, silent thread death, no DI
public partial class SyncService : ServiceBase
{
private Thread _worker;
private bool _running;
protected override void OnStart(string[] args)
{
_running = true;
_worker = new Thread(Loop);
_worker.Start();
}
protected override void OnStop()
{
_running = false; // not volatile, may never be seen
}
private void Loop()
{
while (_running)
{
new OrderSync().Run(); // an exception here ends the thread
Thread.Sleep(300000); // stop waits up to 5 minutes
}
}
}
The sleep is the core problem. Once the thread is asleep nothing can wake it, so a stop request
waits for the rest of the five minutes and the Service Control Manager gives up. The _running
flag is read by one thread and written by another without volatile, so the loop may never see
the change. And an unhandled exception in Run ends the thread while the service stays "Running".
The improved recipe
Separate the job from the schedule. The job is a plain class with one method. A generic hosted
service runs any job on a PeriodicTimer, in its own dependency-injection scope, and logs
failures without dying.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Jobs;
public interface IScheduledJob
{
Task RunAsync(CancellationToken ct);
}
public sealed class TimedJobOptions<TJob>
where TJob : class, IScheduledJob
{
public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(5);
public bool RunOnStart { get; set; } = true;
}
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ImproveCode.Jobs;
public sealed class TimedJobService<TJob>(
IServiceScopeFactory scopes,
IOptions<TimedJobOptions<TJob>> options,
ILogger<TimedJobService<TJob>> logger) : BackgroundService
where TJob : class, IScheduledJob
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
TimedJobOptions<TJob> settings = options.Value;
using var timer = new PeriodicTimer(settings.Interval);
if (settings.RunOnStart)
{
await RunOnceAsync(stoppingToken);
}
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await RunOnceAsync(stoppingToken);
}
}
private async Task RunOnceAsync(CancellationToken ct)
{
string job = typeof(TJob).Name;
long started = Stopwatch.GetTimestamp();
try
{
await using AsyncServiceScope scope =
scopes.CreateAsyncScope();
TJob instance =
scope.ServiceProvider.GetRequiredService<TJob>();
await instance.RunAsync(ct);
logger.LogInformation("{Job} finished in {Elapsed}",
job, Stopwatch.GetElapsedTime(started));
}
catch (OperationCanceledException)
when (ct.IsCancellationRequested)
{
throw; // The host is stopping; let ExecuteAsync end.
}
catch (Exception ex)
{
logger.LogError(ex, "{Job} failed after {Elapsed}",
job, Stopwatch.GetElapsedTime(started));
}
}
}
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ImproveCode.Jobs;
public static class TimedJobServiceCollectionExtensions
{
public static IServiceCollection AddTimedJob<TJob>(
this IServiceCollection services,
TimeSpan interval,
bool runOnStart = true)
where TJob : class, IScheduledJob
{
services.AddScoped<TJob>();
services.Configure<TimedJobOptions<TJob>>(o =>
{
o.Interval = interval;
o.RunOnStart = runOnStart;
});
services.AddHostedService<TimedJobService<TJob>>();
return services;
}
}
A job is now an ordinary class that can take any scoped service, such as a DbContext or a typed
HTTP client from Chapter 13:
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Jobs;
public sealed class InvoiceSyncJob(ILogger<InvoiceSyncJob> logger)
: IScheduledJob
{
public async Task RunAsync(CancellationToken ct)
{
logger.LogInformation("Syncing invoices");
// Load pending invoices, push them, mark them sent.
await Task.CompletedTask;
}
}
Registering it takes one line: builder.Services.AddTimedJob<InvoiceSyncJob>(TimeSpan.FromMinutes(5));
How it works
BackgroundService is the base class for long-running work in the Generic Host. The host calls
ExecuteAsync at start-up and passes a stoppingToken that is cancelled when the application is
asked to stop, whether by the Service Control Manager, Ctrl+C or a container's SIGTERM.
PeriodicTimer is the replacement for Thread.Sleep. WaitForNextTickAsync waits without
blocking a thread and returns as soon as the token is cancelled. A stop request now takes
milliseconds, not minutes. The timer also does not drift: ticks are scheduled from the timer's
start, not from the end of the previous run. If a run takes longer than the interval, the missed
tick fires once when the run finishes. Runs never overlap, and they never pile up.
Each run gets its own AsyncServiceScope. Hosted services are singletons, but the job's
dependencies are often scoped, and a DbContext that lives for weeks inside a singleton is a
memory leak and a stale cache. A fresh scope per run gives each run fresh dependencies, disposed at
the end of the run.
The two catch blocks separate the cases that matter. Cancellation during shutdown is rethrown
and ends the loop quietly. Every other exception is logged with the job name and elapsed time, and
the service waits for the next tick. One bad run never ends the schedule. That is deliberate:
since .NET 6, an unhandled exception in ExecuteAsync stops the whole host.
Variations and pitfalls
- Don't block in
ExecuteAsyncbefore the firstawait. The host runsExecuteAsyncsynchronously until it first yields. Heavy synchronous work at the top delays start-up of every other service. If the job is synchronous, start withawait Task.Yield();. - Testing. The job class has no timer and no host, so a unit test can create it and call
RunAsyncdirectly. That alone usually justifies the split.
On .NET Framework
The Generic Host packages support .NET Framework 4.6.2 and later, so BackgroundService works in
an old service project. PeriodicTimer needs .NET 6. On .NET Framework, use
await Task.Delay(interval, stoppingToken) instead. It is still cancellable, which is the part
that fixes the stop problem.