Optimistic timeout
The delegate does support cancellation.
The to be executed delegate
private static async Task SomeMethodAsync(CancellationToken ct = default)
{
Console.WriteLine($"{nameof(SomeMethodAsync)} has been called.");
await Task.Delay(15000, ct); //It is aware of the CancellationToken
}
The timeout policy
private static AsyncTimeoutPolicy GetTimeoutPolicy
=> Policy
.TimeoutAsync(
TimeSpan.FromMilliseconds(1000),
TimeoutStrategy.Optimistic,
(context, timeout, _, exception) =>
{
Console.WriteLine($"{"Timeout",-10}{timeout,-10:ss\\.fff}: {exception.GetType().Name}");
return Task.CompletedTask;
});
The usage
var strategy = GetTimeoutPolicy;
var result = await strategy.ExecuteAsync(async (ct) => await SomeMethodAsync(ct), CancellationToken.None);
The output
SomeMethodAsync has been called.
Timeout 01.000 : TaskCanceledException
Unhandled exception. Polly.Timeout.TimeoutRejectedException: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
...
Pessimistic timeout
The delegate does not support cancellation.
The to be executed delegate
private static async Task SomeMethodAsync(CancellationToken ct = default)
{
Console.WriteLine($"{nameof(SomeMethodAsync)} has been called.");
await Task.Delay(15000); //It is NOT aware of the CancellationToken
}
The timeout policy
private static AsyncTimeoutPolicy GetTimeoutPolicy
=> Policy
.TimeoutAsync(
TimeSpan.FromMilliseconds(1000),
TimeoutStrategy.Pessimistic,
(context, timeout, _, exception) =>
{
Console.WriteLine($"{"Timeout",-10}{timeout,-10:ss\\.fff}: {exception.GetType().Name}");
return Task.CompletedTask;
});
The usage
var strategy = GetTimeoutPolicy;
var result = await strategy.ExecuteAsync(async () => await SomeMethodAsync());
The output
SomeMethodAsync has been called.
Timeout 01.000 : TaskCanceledException
Unhandled exception. Polly.Timeout.TimeoutRejectedException: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
...