Select Page

A periodic loop can start a second job while the first is still unfinished, even when it awaits every timer tick. Await the job itself before requesting the next tick. This tutorial makes the overlap reproducible, then checks a sequential loop through normal work, cancellation and failure.

Both complete programs were compiled and run as .NET 10 console applications in a pinned, offline Linux SDK container on 8 November 2026, with nullable analysis and warnings treated as errors. They use only the base class library. Save each program separately as Program.cs in a console project targeting net10.0.

Choose the scheduling contract

Microsoft documents that System.Threading.Timer callbacks can execute simultaneously when a callback outlasts its interval. Here we use PeriodicTimer to put the work under one loop’s control. Its contract permits only one outstanding tick wait per timer.

That single-consumer rule does not serialize jobs you detach from the loop. The loop must retain ownership of each job until it finishes. The guarantee here covers one loop instance and work whose returned task represents all its activity. Multiple application instances need their own coordination.

Reproduce overlap without relying on a slow machine

The first program collects two job tasks without awaiting either inside the loop. Each job increments active before reaching an incomplete gate. The gate stays closed until both ticks have been consumed, so the assertion must see two unfinished jobs. This tests overlapping lifetimes; the jobs need not execute CPU instructions simultaneously.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

for (int round = 0; round < 25; round++)
{
    using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(5));
    using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(1));
    var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    var jobs = new List<Task>();
    int active = 0, finished = 0;
    try
    {
        for (int tick = 0; tick < 2; tick++)
        {
            if (!await timer.WaitForNextTickAsync(stop.Token))
                throw new InvalidOperationException("Timer stopped early.");
            jobs.Add(WorkAsync()); // The loop does not await the job.
        }
        if (active != 2)
            throw new InvalidOperationException("Expected two unfinished jobs.");
    }
    finally
    {
        release.TrySetResult();
        await Task.WhenAll(jobs).WaitAsync(TimeSpan.FromSeconds(5));
    }
    if (active != 0 || finished != 2)
        throw new InvalidOperationException("Jobs were not drained.");

    async Task WorkAsync()
    {
        Interlocked.Increment(ref active);
        try { await release.Task.WaitAsync(stop.Token); }
        finally
        {
            Interlocked.Decrement(ref active);
            Interlocked.Increment(ref finished);
        }
    }
}
Console.WriteLine("25 rounds: two jobs overlapped; all 50 jobs drained.");

Expected stdout:

25 rounds: two jobs overlapped; all 50 jobs drained.

The gate is test orchestration, standing in for unfinished asynchronous work. It avoids guessing how long a real request might take. The finally block releases and awaits every job, and each round has bounded waits. Keeping the tasks in a list makes this demonstration safe to drain; a production loop that discards them would lose that ownership.

Await each job and own shutdown

In the next program, RunAsync awaits the job before returning to the tick wait. The surrounding checks are a small executable test harness. The first case completes three jobs and requests shutdown. The next cancels a job after it enters a cancellable wait. Two further checks exercise a pending tick wait and an ordinary job exception.

using System;
using System.Threading;
using System.Threading.Tasks;

for (int round = 0; round < 25; round++)
{
    using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(5));
    int active = 0, peak = 0, completed = 0, cleanup = 0;
    await RunAsync(stop.Token, async token =>
    {
        active++;
        peak = Math.Max(peak, active);
        try
        {
            await Task.Delay(3, token);
            completed++;
            if (completed == 3) stop.Cancel();
        }
        finally { active--; }
    }, () => cleanup++);
    Check(peak == 1 && active == 0 && completed == 3 && cleanup == 1);

    using var cancelWork = new CancellationTokenSource(TimeSpan.FromSeconds(5));
    var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    int workCleanup = 0, loopCleanup = 0;
    Task running = RunAsync(cancelWork.Token, async token =>
    {
        entered.TrySetResult();
        try { await Task.Delay(Timeout.Infinite, token); }
        finally { workCleanup++; }
    }, () => loopCleanup++);
    try
    {
        await entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
    }
    finally
    {
        cancelWork.Cancel();
        await running.WaitAsync(TimeSpan.FromSeconds(5));
    }
    Check(workCleanup == 1 && loopCleanup == 1);

    using var timer = new PeriodicTimer(TimeSpan.FromDays(1));
    using var cancelWait = new CancellationTokenSource();
    Task<bool> waiting = timer.WaitForNextTickAsync(cancelWait.Token).AsTask();
    Check(!waiting.IsCompleted);
    cancelWait.Cancel();
    bool canceled = false;
    try { await waiting.WaitAsync(TimeSpan.FromSeconds(5)); }
    catch (OperationCanceledException) when (cancelWait.IsCancellationRequested)
    { canceled = true; }
    Check(canceled);
    timer.Dispose();
    Check(!await timer.WaitForNextTickAsync());

    int faultCleanup = 0;
    bool faultObserved = false;
    using var faultStop = new CancellationTokenSource(TimeSpan.FromSeconds(5));
    try
    {
        await RunAsync(faultStop.Token,
            _ => Task.FromException(new InvalidOperationException("Job failed.")),
            () => faultCleanup++);
    }
    catch (InvalidOperationException e) when (e.Message == "Job failed.")
    { faultObserved = true; }
    Check(faultObserved && faultCleanup == 1);
}
Console.WriteLine("25 rounds: three jobs completed per loop; peak active = 1.");
Console.WriteLine("25 rounds: work cancellation, wait cancellation, disposal and fault cleanup passed.");

static async Task RunAsync(CancellationToken token,
    Func<CancellationToken, Task> work, Action cleanedUp)
{
    using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(1));
    try
    {
        while (await timer.WaitForNextTickAsync(token))
        {
            token.ThrowIfCancellationRequested();
            await work(token);
        }
    }
    catch (OperationCanceledException) when (token.IsCancellationRequested)
    {
        // This loop treats its owner's cancellation as normal shutdown.
    }
    finally { cleanedUp(); }
}

static void Check(bool condition)
{
    if (!condition) throw new InvalidOperationException("Assertion failed.");
}

Expected stdout:

25 rounds: three jobs completed per loop; peak active = 1.
25 rounds: work cancellation, wait cancellation, disposal and fault cleanup passed.

The first case asserts a peak of exactly one active job, three completions, no work left active and one loop cleanup. The cancellation case awaits the loop’s completion before checking both cleanup counters. The failure case verifies that an ordinary job exception reaches the caller and still runs loop cleanup. Each case repeats 25 times; these are behavior checks, not timing measurements.

RunAsync treats cancellation requested through its owner token as normal shutdown. Other exceptions propagate. Its using declaration disposes the timer when the method exits. The job must also honor cancellation: passing a token cannot interrupt arbitrary work that ignores it. For more on passing tokens through asynchronous code, see CancellationToken propagation across application layers.

Understand what happens to missed ticks

The WaitForNextTickAsync contract says ticks arriving between waits merge into one pending notification. A long job can therefore be followed immediately by another job. This is not a fresh full-period delay after completion, and it does not preserve every scheduled occurrence.

The same API distinguishes shutdown paths: disposing the timer makes a tick wait return false; canceling the wait produces cancellation and leaves the timer running. The harness checks both outcomes separately. Its one-day timer prevents an ordinary tick from racing the explicit wait-cancellation check.

Use this pattern for periodic refresh or polling when one run at a time is the intended policy and merged ticks are acceptable. If every occurrence must be retained, design an explicit durable work queue. For shared state accessed by other workers, also review reproducing a C# race condition with a controlled schedule: serializing this loop does not serialize unrelated callers.

Share This