typestar

Timeouts in C#

A deadline the callback cannot talk its way out of.

using Polly;
using Polly.Timeout;

var pipeline = new ResiliencePipelineBuilder()
    .AddTimeout(TimeSpan.FromMilliseconds(50))
    .Build();

try
{
    // a well-behaved callback watches its token; this one never finishes
    pipeline.Execute(token =>
    {
        while (!token.IsCancellationRequested) { }
        token.ThrowIfCancellationRequested();
    });
}
catch (TimeoutRejectedException)
{
    Console.WriteLine("gave up at 50ms, as configured");
}

How it works

  1. AddTimeout takes the budget directly; the pipeline enforces it.
  2. Cooperative cancellation flows through the token argument.
  3. TimeoutRejectedException is the signal the deadline fired.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
416
Tokens
70
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 2 of 2 in Resilience with Polly, step 9 of 16 in The open ecosystem.

← Previous Next →

Timeouts in other languages