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 comparing PeriodicTimer against Task.Delay loops in C# and .NET

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 via WaitForNextTickAsync(CancellationToken) instead of registering fire-and-forget callbacks.
  • Because your code awaits WaitForNextTickAsync sequentially, 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 TimeProvider into new PeriodicTimer(period, timeProvider) so you can test intervals deterministically using FakeTimeProvider without waiting real seconds.
  • Remember the single-consumer rule: only one call to WaitForNextTickAsync may be in flight at a time, and WaitForNextTickAsync throws OperationCanceledException (or TaskCanceledException) when the CancellationToken is canceled rather than returning false.

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 Core BackgroundService classes.
  • TimeProvider constructor 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.Timer invokes a synchronous TimerCallback on a ThreadPool thread. Using async void inside 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 of DoWorkAsync().
  • PeriodicTimer keeps the async/await control 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:

  1. using var timer ensures PeriodicTimer.Dispose() runs when ExecuteAsync exits, releasing the underlying timer resources.
  2. Catching OperationCanceledException when stoppingToken.IsCancellationRequested is true prevents noisy unhandled-cancellation logs during graceful host shutdown. As Microsoft Learn’s Timers guide notes, calling Dispose() causes WaitForNextTickAsync to return false, whereas canceling the CancellationToken throws TaskCanceledException (a subclass of OperationCanceledException).
  3. Injecting TimeProvider lets unit tests advance a FakeTimeProvider by 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 WaitForNextTickAsync concurrently from two tasks. Per Microsoft Learn’s PeriodicTimer remarks, PeriodicTimer is designed for one consumer at a time—only a single WaitForNextTickAsync call may be awaiting at any moment.
  • Letting an unhandled exception inside RunHealthCheckAsync kill the loop. If a transient network call throws inside the while body without a localized try/catch, the BackgroundService stops polling completely. Catch transient errors inside the loop body and log them so the next tick still runs.
  • Assuming WaitForNextTickAsync(ct) returns false on token cancellation. Dispose() returns false; token cancellation throws OperationCanceledException. Handle both cleanly.
  • Forgetting Period validation. Passing TimeSpan.Zero or a negative TimeSpan (other than Timeout.InfiniteTimeSpan depending on runtime/version) throws ArgumentOutOfRangeException. Always pass a positive interval like TimeSpan.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.

Sources