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
AddTimeouttakes the budget directly; the pipeline enforces it.- Cooperative cancellation flows through the token argument.
TimeoutRejectedExceptionis the signal the deadline fired.
Keywords and builtins used here
catchnewtryusingvarwhile
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.
Step 2 of 2 in Resilience with Polly, step 9 of 16 in The open ecosystem.