How to Use PeriodicTimer in C# and .NET Instead of Task.Delay Loops
Most .NET background workers need to run a health check, flush a metrics batch, or poll a queue on a fixed interval. For years, developers reached for either while (!ct.IsCancellationRequested) { await DoWorkAsync(); await Task.Delay(period, ct); }—which drifts by however long DoWorkAsync() takes—or System.Threading.Timer, whose callback-based design can fire overlapping executions if a previous tick runs long. System.Threading.PeriodicTimer solves both problems with a clean await loop built for modern async C#.
Editorial illustration: PeriodicTimer awaits each tick asynchronously without overlapping callbacks.
Summary
PeriodicTimer(introduced in .NET 6) is a .NET runtime/BCL API that lets an async loop await ticks viaWaitForNextTickAsync(CancellationToken)instead of registering fire-and-forget callbacks.- Because your code awaits
WaitForNextTickAsyncsequentially, ticks never overlap—if one iteration takes longer than the interval, the next tick simply runs without spawning concurrent callbacks. - On .NET 8 and newer, pass a
TimeProviderintonew PeriodicTimer(period, timeProvider)so you can test intervals deterministically usingFakeTimeProviderwithout waiting real seconds. - Remember the single-consumer rule: only one call to
WaitForNextTickAsyncmay be in flight at a time, andWaitForNextTickAsyncthrowsOperationCanceledException(orTaskCanceledException) when theCancellationTokenis canceled rather than returningfalse.
Prerequisites: .NET API vs. C# Language
Clarifying where PeriodicTimer lives helps when targeting multiple .NET versions:
- .NET Runtime / BCL (
System.Threading.PeriodicTimer): Introduced in .NET 6, available in all modern .NET releases (.NET 8,.NET 9,.NET 10,.NET 11) for console apps, Worker Services, and ASP.NET CoreBackgroundServiceclasses. TimeProviderconstructor overload: Added in .NET 8 (PeriodicTimer(TimeSpan period, TimeProvider timeProvider)).- C# Language & IDE: Works with any recent C# version (C# 10+) and any .NET-capable IDE such as Visual Studio 2026, Visual Studio 2022, or VS Code with C# Dev Kit.
Why PeriodicTimer beats Task.Delay and System.Threading.Timer
As explained in Microsoft Learn’s Timers overview, .NET provides multiple timers for different scenarios:
System.Threading.Timerinvokes a synchronousTimerCallbackon a ThreadPool thread. Usingasync voidinside that callback is dangerous, and if one tick takes 6 seconds on a 5-second interval, two callbacks can run concurrently unless you add manual locking.while (...) { await DoWorkAsync(); await Task.Delay(period); }avoids overlap, yet every iteration’s start time drifts by the duration ofDoWorkAsync().PeriodicTimerkeeps theasync/awaitcontrol flow directly inside your method scope, avoids overlapping ticks, and disposes cleanly without callback-after-dispose races.
Practical example: BackgroundService with PeriodicTimer
Here is a clean ASP.NET Core / Worker Service example targeting .NET 8+ (or .NET 10):
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public sealed class HeartbeatWorker(
TimeProvider timeProvider,
ILogger<HeartbeatWorker> logger) : BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(Interval, timeProvider);
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await RunHealthCheckAsync(stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// Expected shutdown signal from host
}
}
private Task RunHealthCheckAsync(CancellationToken ct)
{
logger.LogInformation("Health check ran at {UtcNow}", timeProvider.GetUtcNow());
return Task.CompletedTask;
}
}
Notice three important details in this pattern:
using var timerensuresPeriodicTimer.Dispose()runs whenExecuteAsyncexits, releasing the underlying timer resources.- Catching
OperationCanceledExceptionwhenstoppingToken.IsCancellationRequestedis true prevents noisy unhandled-cancellation logs during graceful host shutdown. As Microsoft Learn’s Timers guide notes, callingDispose()causesWaitForNextTickAsyncto returnfalse, whereas canceling theCancellationTokenthrowsTaskCanceledException(a subclass ofOperationCanceledException). - Injecting
TimeProviderlets unit tests advance aFakeTimeProviderby 30 seconds instantly instead of sleeping in CI pipelines.
For related async patterns, review using CancellationToken properly in async C# methods and bounded channels for backpressure in C#.
Common mistakes
- Calling
WaitForNextTickAsyncconcurrently from two tasks. Per Microsoft Learn’sPeriodicTimerremarks,PeriodicTimeris designed for one consumer at a time—only a singleWaitForNextTickAsynccall may be awaiting at any moment. - Letting an unhandled exception inside
RunHealthCheckAsynckill the loop. If a transient network call throws inside thewhilebody without a localizedtry/catch, theBackgroundServicestops polling completely. Catch transient errors inside the loop body and log them so the next tick still runs. - Assuming
WaitForNextTickAsync(ct)returnsfalseon token cancellation.Dispose()returnsfalse; token cancellation throwsOperationCanceledException. Handle both cleanly. - Forgetting
Periodvalidation. PassingTimeSpan.Zeroor a negativeTimeSpan(other thanTimeout.InfiniteTimeSpandepending on runtime/version) throwsArgumentOutOfRangeException. Always pass a positive interval likeTimeSpan.FromSeconds(30).
Why this matters
Background polling loops look trivial until shutdown hangs, two ticks run at once and corrupt shared state, or unit tests take 60 seconds to run. PeriodicTimer paired with TimeProvider gives you predictable, non-overlapping async execution and fast tests in about ten lines of code.
My Take
If you are writing any new .NET 8 or .NET 10 worker loop today, skip Task.Delay loops and callback-based System.Threading.Timer completely—PeriodicTimer with TimeProvider is cleaner, safer on shutdown, and far easier to unit test.
Conclusion
Use PeriodicTimer inside a using block with while (await timer.WaitForNextTickAsync(stoppingToken)), pass TimeProvider on .NET 8+ for deterministic testing, catch transient work exceptions inside the loop, and handle OperationCanceledException cleanly on host shutdown.