Select Page

A timeout answers how long you are willing to wait. Cancellation asks work to stop. A retry policy decides whether another attempt is justified. Combining these into one catch-and-repeat loop can start a second operation while the first still runs, or repeat work after the caller has canceled.

This tutorial builds a small BCL-only policy with three explicit decisions: retry only a known transient failure, allow at most three attempts, and treat an expired attempt budget as terminal. It also preserves caller cancellation during work and between attempts.

Verified 8 November 2026. The complete program targets .NET 10 and was compiled and run in a pinned Linux SDK container with networking disabled. Its exact output was asserted across 20 rounds. The timings trigger test paths; they are not latency guarantees.

Choose the outcome before choosing the mechanism

Policy used by this example
Event Decision
Explicit transient failure Retry after a cancelable pause, up to three total attempts.
Other failure Propagate immediately.
Attempt requests cancellation after its budget If the operation throws cancellation and the caller is still active, report a terminal TimeoutException.
Caller cancellation Propagate cancellation; start no further attempt.

Three total attempts means one initial call and at most two retries. The custom TransientFailure type is a test contract, not a classification of real network exceptions. A production adapter needs a documented list of retryable failures. Consider idempotency: losing a response does not prove the server did no work. Microsoft’s retry pattern guidance discusses transient failures, duplicate side effects and nested retries.

First prove that timing out a wait leaves work behind

Task.WaitAsync returns a task representing a wait that can end on timeout. In Reproduce below, an infinite cancellable delay is already pending. A zero-duration wait must throw TimeoutException, while the original task remains incomplete and its cancellation source remains active. This removes scheduling guesses from the reproduction.

The finally block then explicitly cancels the owned operation and awaits its completion. The exit counter must be one. Starting a retry immediately after the timed-out wait would otherwise leave this first operation pending.

Run the complete policy and its failure tests

Create a .NET 10 console project and replace Program.cs with the entire program below. No package references are needed. The Run method awaits each operation directly. It gives each attempt a fresh source linked to the caller, then uses CancelAfter to request cancellation after the attempt budget. Microsoft’s CancellationTokenSource reference documents linking, delayed cancellation and source disposal.

This is a cooperative budget: the operation must honor its token and return a task covering all its work, including cleanup. If it ignores cancellation, Run can keep waiting; it does not impose a hard execution deadline. A successful operation is returned as success even if cancellation races with completion. The timeout translation applies only to a cancellation exception observed while the attempt source is canceled and the caller is not. Caller cancellation is checked when classifying that exception; simultaneous signals do not reveal which happened first.

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

class Program
{
    sealed class TransientFailure : Exception { }
    static readonly TimeSpan Budget = TimeSpan.FromMilliseconds(20);
    static readonly TimeSpan Guard = TimeSpan.FromSeconds(5);

    static void Require(bool condition, string message)
    {
        if (!condition) throw new Exception(message);
    }

    static async Task Expect<T>(Func<Task> action) where T : Exception
    {
        try { await action(); }
        catch (T) { return; }
        throw new Exception($"Expected {typeof(T).Name}");
    }

    static async Task<string> Run(
        Func<CancellationToken, Task<string>> operation,
        CancellationToken caller, int maxAttempts, TimeSpan attemptBudget,
        Action? onRetry = null)
    {
        if (maxAttempts < 1 || attemptBudget <= TimeSpan.Zero)
            throw new ArgumentOutOfRangeException(nameof(maxAttempts));

        for (int number = 1; ; number++)
        {
            caller.ThrowIfCancellationRequested();
            using var attempt = CancellationTokenSource.CreateLinkedTokenSource(caller);
            attempt.CancelAfter(attemptBudget);
            try
            {
                return await operation(attempt.Token);
            }
            catch (OperationCanceledException error)
                when (!caller.IsCancellationRequested && attempt.IsCancellationRequested)
            {
                // This policy treats an expired attempt as terminal.
                throw new TimeoutException("Attempt budget expired.", error);
            }
            catch (TransientFailure) when (number < maxAttempts)
            {
                caller.ThrowIfCancellationRequested();
                onRetry?.Invoke();
                await Task.Delay(10, caller);
            }
        }
    }

    static async Task Reproduce()
    {
        using var stop = new CancellationTokenSource();
        int exits = 0;
        async Task Pending()
        {
            try { await Task.Delay(Timeout.Infinite, stop.Token); }
            finally { exits++; }
        }
        Task work = Pending();
        try
        {
            await Expect<TimeoutException>(() => work.WaitAsync(TimeSpan.Zero));
            Require(!work.IsCompleted && !stop.IsCancellationRequested,
                "Timing out the wait unexpectedly stopped the work.");
        }
        finally
        {
            stop.Cancel();
            await Expect<OperationCanceledException>(() => work.WaitAsync(Guard));
        }
        Require(exits == 1 && work.IsCanceled, "Pending work was not drained.");
    }

    static async Task CheckPolicies()
    {
        int calls = 0, exits = 0;
        async Task<string> Eventually(CancellationToken token)
        {
            try
            {
                token.ThrowIfCancellationRequested();
                await Task.CompletedTask;
                if (++calls < 3) throw new TransientFailure();
                return "ok";
            }
            finally { exits++; }
        }
        string result = await Run(Eventually, CancellationToken.None, 3, Guard);
        Require(result == "ok" && calls == 3 && exits == 3, "Retry success failed.");

        calls = 0;
        await Expect<TransientFailure>(() => Run(_ =>
        {
            calls++;
            return Task.FromException<string>(new TransientFailure());
        }, CancellationToken.None, 3, Guard));
        Require(calls == 3, "Retry count was not bounded.");

        calls = 0;
        await Expect<InvalidOperationException>(() => Run(_ =>
        {
            calls++;
            return Task.FromException<string>(new InvalidOperationException());
        }, CancellationToken.None, 3, Guard));
        Require(calls == 1, "Permanent failure was retried.");

        calls = 0; exits = 0;
        async Task<string> Slow(CancellationToken token)
        {
            calls++;
            try { await Task.Delay(Timeout.Infinite, token); return "unreachable"; }
            finally { exits++; }
        }
        await Expect<TimeoutException>(() => Run(Slow, CancellationToken.None, 3, Budget));
        Require(calls == 1 && exits == 1, "Timeout retried or skipped cleanup.");

        calls = 0; exits = 0;
        using var caller = new CancellationTokenSource();
        await Expect<OperationCanceledException>(() => Run(async token =>
        {
            calls++;
            try
            {
                caller.Cancel();
                await Task.Delay(Timeout.Infinite, token);
                return "unreachable";
            }
            finally { exits++; }
        }, caller.Token, 3, Guard));
        Require(calls == 1 && exits == 1, "Caller cancellation was retried.");

        calls = 0;
        using var backoff = new CancellationTokenSource();
        await Expect<OperationCanceledException>(() => Run(_ =>
        {
            calls++;
            return Task.FromException<string>(new TransientFailure());
        }, backoff.Token, 3, Guard, () => backoff.Cancel()));
        Require(calls == 1, "Canceled backoff started another attempt.");

        calls = 0;
        await Expect<OperationCanceledException>(() => Run(_ =>
        {
            calls++;
            return Task.FromResult("unexpected");
        }, backoff.Token, 3, Guard));
        Require(calls == 0, "Already canceled caller started work.");
    }

    static async Task Main()
    {
        for (int round = 0; round < 20; round++)
        {
            await Reproduce().WaitAsync(Guard);
            await CheckPolicies().WaitAsync(Guard);
        }
        Console.WriteLine("20 rounds: timed-out waits left work running; cleanup observed.");
        Console.WriteLine("20 rounds: transient success, retry limit and permanent failure passed.");
        Console.WriteLine("20 rounds: timeout, caller cancellation, backoff and pre-cancel checks passed.");
    }
}

Expected output:

20 rounds: timed-out waits left work running; cleanup observed.
20 rounds: transient success, retry limit and permanent failure passed.
20 rounds: timeout, caller cancellation, backoff and pre-cancel checks passed.

What the assertions establish

Each round first reproduces the abandoned-wait problem and drains that work. It then checks success on attempt three, exhaustion at exactly three calls, and a permanent failure after one call. The slow operation observes the 20-millisecond cancellation request; its finally block must run before the terminal timeout reaches the test. No assertion depends on cancellation occurring at exactly 20 milliseconds.

The caller-cancellation test requests cancellation from inside the operation and checks its cleanup. The onRetry hook is test instrumentation: it cancels the caller immediately before the backoff delay so the cancellation path is repeatable. The delay must cancel without a second operation starting. An already canceled token must prevent even the initial call. Five-second WaitAsync guards make a stalled test fail; a guard timeout is not accepted as a successful policy outcome.

The fixed ten-millisecond pause keeps this lab small. It is not a deployment recommendation. Choose delay and attempt limits for the dependency, avoid retrying again in a second layer, and test whether repeated side effects are safe. See the retry pattern considerations.

Keep the caller’s total budget separate

An attempt budget restarts for every call. If the whole workflow has a deadline, supply a caller token whose owner requests cancellation for that deadline; pass it through both work and backoff. This program tests caller cancellation, not a separate timer for the whole workflow. It also does not test HTTP status handling, remote rollback or service load.

For the token wiring behind this policy, continue with CancellationToken propagation across application layers. If you launch several independent operations, Task.WhenAll and partial failure handling explains how to retain and observe their individual outcomes.

Share This