Timeouts and retries
Timeouts and retries
A timeout limits how long an operation or caller waits; cancellation requests that work stop cooperatively. A retry starts another attempt after an eligible failure. A total deadline must include attempts and delays, not just a limit on their count.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Timeout a wait, not necessarily the work
Task.WaitAsync can stop a caller waiting without terminating the underlying task. Zero timeout with a deliberately pending task demonstrates this without a clock race.
using System;using System.Threading.Tasks;var gate = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);try { await gate.Task.WaitAsync(TimeSpan.Zero); }catch (TimeoutException) { Console.WriteLine("timed out"); }Console.WriteLine(gate.Task.IsCompleted);gate.SetResult(8);Console.WriteLine(await gate.Task);The original task remains pending until explicitly completed. Real callers must retain ownership or request cancellation and observe the outcome.
Expected output (reasoned, not executed):
timed outFalse8Retry only eligible failures
This offline read-only mock fails twice with a deliberately designated transient exception. A finite loop retries only that exception and allows the final failure to propagate. Production retries need bounded backoff with jitter and cancellation.
using System;using System.Threading.Tasks;int attempts = 0;for (int attempt = 1; attempt <= 3; attempt++){ try { Console.WriteLine(await ReadAsync()); break; } catch (TemporaryFailure) when (attempt < 3) { Console.WriteLine("retry"); }}Task<string> ReadAsync() => ++attempts < 3 ? Task.FromException<string>(new TemporaryFailure()) : Task.FromResult("catalog ready");sealed class TemporaryFailure : Exception { }The first two failures qualify; the third attempt succeeds. There is no catch-all or silent failure on exhaustion.
Expected output (reasoned, not executed):
retryretrycatalog readyAccount for a total budget
Use a monotonic elapsed clock for production deadlines. This arithmetic-only model uses fixed elapsed milliseconds; it does not simulate actual timers. Attempt timeout is capped by the remaining budget after a proposed delay.
using System;Console.WriteLine(NextAllowance(1000, 760, 100, 300));Console.WriteLine(NextAllowance(1000, 950, 100, 300));static int NextAllowance(int budget, int elapsed, int delay, int cap) => Math.Max(0, Math.Min(cap, budget - elapsed - delay));Only 140 ms remain after the first delay. In the second case there is no time for another attempt. Inputs are small nonnegative fixture values.
Expected output (reasoned, not executed):
1400Common mistakes and edge cases
Do not retry validation errors, canceled operations or arbitrary mutations. A timeout does not prove a remote write failed; use a documented idempotency contract and reconcile uncertain outcomes. Bound concurrency and retry amplification, propagate a cancellation token, and avoid restarting work while a previous attempt is still running unless explicitly safe.
Practice and recap
Given a total budget of 900 ms, elapsed 620 ms, delay 80 ms and cap 250 ms, calculate the allowance. Repeat with elapsed 850 ms.
Hint: Subtract both elapsed time and the next delay; clamp at zero and the cap.
Learning objective: Distinguish timeout budget from retry count. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timeouts and retries — knowledge check
Apply the lesson concepts to the following scenarios.
What is guaranteed by the WaitAsync timeout in the fixture?
When should the mock retry?
What is an idempotency concern?
Budget 1000, elapsed 760, delay 100, cap 300: allowance?
Which clock is appropriate for elapsed deadlines?