RetryPolicy Class

Namespace
Kampute.Resilience
Assembly
  • Kampute.Resilience.dll

Definition

Represents a retry policy: a strategy that decides whether and when to retry, the exceptions that are retried, and callbacks for each retry.
public sealed class RetryPolicy
Inheritance

Remarks

A policy is immutable. Each configuration method returns a new policy and leaves the original unchanged, so a policy can be built once, stored, and shared by any number of concurrent executions. Each execution keeps its own retry count and elapsed time.

Without a call to a RetryOn method, the policy retries every exception except an OperationCanceledException thrown after the caller's token is canceled, which is never retried. Call RetryOnResult<T>(Func<T, bool>) to also retry returned values; it returns a RetryPolicy<T> that keeps this policy's configuration.

Callbacks run on the execution path. If an exception classifier throws, the operation's exception propagates as if it was not retried; an exception from a delay override or retry handler propagates in place of the operation's outcome, and the operation is not retried.

Examples

This policy retries timeouts up to five times with exponential backoff and logs each retry:
var retry = RetryStrategies.Exponential(TimeSpan.FromSeconds(1))
    .WithMaxRetries(5)
    .RetryOn<TimeoutException>()
    .OnRetry(context => Console.WriteLine($"Attempt {context.AttemptNumber} failed; retrying in {context.Delay}."));

var value = await retry.ExecuteAsync(ct => LoadAsync(ct), cancellationToken);

Constructors

RetryPolicy(IRetryStrategy)

Initializes a new instance of the RetryPolicy class that retries every exception as the strategy decides.
public RetryPolicy(IRetryStrategy strategy)

Parameters

strategy IRetryStrategy
The strategy that decides whether and when to retry.

Exceptions

ArgumentNullException
Thrown if strategy is null.

Properties

Strategy

Gets the strategy of this policy.
public IRetryStrategy Strategy { get; }

Property Value

IRetryStrategy
The IRetryStrategy that decides whether and when to retry.

Methods

Execute(Action<CancellationToken>, CancellationToken)

Runs a blocking operation and retries it as this policy decides when it fails.
public void Execute(Action<CancellationToken> operation, CancellationToken cancellationToken = default)

Parameters

operation Action<CancellationToken>
The operation to run. It receives cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Exceptions

ArgumentNullException
Thrown if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Execute<T>(Func<CancellationToken, T>, CancellationToken)

Runs a blocking operation that returns a value and retries it as this policy decides when it fails.
public T Execute<T>(Func<CancellationToken, T> operation, CancellationToken cancellationToken = default)

Type Parameters

T
The type of the value the operation returns.

Parameters

operation Func<CancellationToken, T>
The operation to run. It receives cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

T
The value returned by the first successful run of the operation.

Exceptions

ArgumentNullException
Thrown if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Execute<TState>(TState, Action<TState, CancellationToken>, CancellationToken)

Runs a blocking operation that receives a state, and retries it as this policy decides when it fails.
public void Execute<TState>(TState state, Action<TState, CancellationToken> operation, CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.

Parameters

state TState
The state passed to every attempt of the operation.
operation Action<TState, CancellationToken>
The operation to run. It receives state and cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Exceptions

ArgumentNullException
Thrown if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.

Execute<TState, T>(TState, Func<TState, CancellationToken, T>, CancellationToken)

Runs a blocking operation that receives a state and returns a value, and retries it as this policy decides when it fails.
public T Execute<TState, T>(TState state, Func<TState, CancellationToken, T> operation, CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.
T
The type of the value the operation returns.

Parameters

state TState
The state passed to every attempt of the operation.
operation Func<TState, CancellationToken, T>
The operation to run. It receives state and cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

T
The value returned by the first successful run of the operation.

Exceptions

ArgumentNullException
Thrown if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.

ExecuteAsync(Func<CancellationToken, Task>, CancellationToken)

Runs an asynchronous operation and retries it as this policy decides when it fails.
public Task ExecuteAsync(Func<CancellationToken, Task> operation, CancellationToken cancellationToken = default)

Parameters

operation Func<CancellationToken, Task>
The operation to run. It receives cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

Task
A task that completes when the operation succeeds.

Exceptions

ArgumentNullException
Thrown, before a task is returned, if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

ExecuteAsync<T>(Func<CancellationToken, Task<T>>, CancellationToken)

Runs an asynchronous operation that returns a value and retries it as this policy decides when it fails.
public Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken = default)

Type Parameters

T
The type of the value the operation returns.

Parameters

operation Func<CancellationToken, Task<T>>
The operation to run. It receives cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

Task<T>
A task that resolves to the value returned by the first successful run of the operation.

Exceptions

ArgumentNullException
Thrown, before a task is returned, if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

ExecuteAsync<TState>(TState, Func<TState, CancellationToken, Task>, CancellationToken)

Runs an asynchronous operation that receives a state, and retries it as this policy decides when it fails.
public Task ExecuteAsync<TState>(TState state, Func<TState, CancellationToken, Task> operation, CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.

Parameters

state TState
The state passed to every attempt of the operation.
operation Func<TState, CancellationToken, Task>
The operation to run. It receives state and cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

Task
A task that completes when the operation succeeds.

Exceptions

ArgumentNullException
Thrown, before a task is returned, if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.

ExecuteAsync<TState, T>(TState, Func<TState, CancellationToken, Task<T>>, CancellationToken)

Runs an asynchronous operation that receives a state and returns a value, and retries it as this policy decides when it fails.
public Task<T> ExecuteAsync<TState, T>(TState state, Func<TState, CancellationToken, Task<T>> operation, CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.
T
The type of the value the operation returns.

Parameters

state TState
The state passed to every attempt of the operation.
operation Func<TState, CancellationToken, Task<T>>
The operation to run. It receives state and cancellationToken.
cancellationToken CancellationToken optional
A token for canceling the operation and the waits between attempts (optional).

Returns

Task<T>
A task that resolves to the value returned by the first successful run of the operation.

Exceptions

ArgumentNullException
Thrown, before a task is returned, if operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.

Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.

OnRetry(Action<RetryContext>)

Creates a policy that invokes a handler for each approved retry.
public RetryPolicy OnRetry(Action<RetryContext> handler)

Parameters

handler Action<RetryContext>
The handler, which receives the failed attempt and the delay that execution waits before the retry.

Returns

RetryPolicy
A new policy that invokes the handlers of this policy and then handler.

Exceptions

ArgumentNullException
Thrown if handler is null.

Remarks

Handlers run before the wait, and only when a retry follows: not when the strategy allows no more retries, and not for exceptions that are not retried. If a handler throws, later handlers do not run.

OverrideDelay(Func<RetryContext, TimeSpan>)

Creates a policy that replaces the strategy's delay with one computed from the failed attempt.
public RetryPolicy OverrideDelay(Func<RetryContext, TimeSpan> delay)

Parameters

delay Func<RetryContext, TimeSpan>
A function that receives the failed attempt, whose RetryContext.Delay is the delay that the strategy proposes, and returns the nonnegative delay to wait. Return RetryContext.Delay to keep the proposed delay.

Returns

RetryPolicy
A new policy whose delays delay selects. It replaces any delay override of this policy.

Exceptions

ArgumentNullException
Thrown if delay is null.

Remarks

The override runs only after the strategy allows a retry, and its delay replaces the proposed delay after all strategy modifiers, so it can exceed a delay cap or the time left under an elapsed-time limit. Enforce any required deadline in the override or with the caller's cancellation token.

A negative delay throws ArgumentOutOfRangeException from the execution, without a retry. A delay longer than int.MaxValue milliseconds stops retrying, as when the strategy allows no more retries.

RetryOn(Func<Exception, bool>)

Creates a policy that also retries the exceptions that satisfy a condition.
public RetryPolicy RetryOn(Func<Exception, bool> predicate)

Parameters

predicate Func<Exception, bool>
A function that returns true for the exceptions to retry.

Returns

RetryPolicy
A new policy that retries the exceptions this policy retries and the exceptions that predicate selects.

Exceptions

ArgumentNullException
Thrown if predicate is null.

Remarks

The first RetryOn call limits retries to the exceptions it selects; later calls add to them. If predicate throws, the operation's exception propagates without a retry.

RetryOn<TException>()

Creates a policy that also retries exceptions of the specified type.
public RetryPolicy RetryOn<TException>()
	where TException : Exception

Type Parameters

TException
The type of the exceptions to retry, including derived types.

Returns

RetryPolicy
A new policy that retries the exceptions this policy retries and the exceptions of type TException.

Remarks

The first RetryOn call limits retries to the exceptions it selects; later calls add to them.

RetryOn<TException>(Func<TException, bool>)

Creates a policy that also retries exceptions of the specified type that satisfy a condition.
public RetryPolicy RetryOn<TException>(Func<TException, bool> predicate)
	where TException : Exception

Type Parameters

TException
The type of the exceptions to retry, including derived types.

Parameters

predicate Func<TException, bool>
A function that returns true for the exceptions of type TException to retry.

Returns

RetryPolicy
A new policy that retries the exceptions this policy retries and the exceptions that predicate selects.

Exceptions

ArgumentNullException
Thrown if predicate is null.

Remarks

The first RetryOn call limits retries to the exceptions it selects; later calls add to them. If predicate throws, the operation's exception propagates without a retry.

RetryOnResult<T>(Func<T, bool>)

Creates a policy for operations returning T that also retries the results that satisfy a condition.
public RetryPolicy<T> RetryOnResult<T>(Func<T, bool> predicate)

Type Parameters

T
The type returned by the operations the new policy runs.

Parameters

predicate Func<T, bool>
A function that returns true for the results to retry.

Returns

RetryPolicy<T>
A new RetryPolicy<T> with this policy's strategy, retried exceptions, delay override, and retry handlers.

Exceptions

ArgumentNullException
Thrown if predicate is null.

Remarks

When the strategy allows no more retries, execution returns the last result even though predicate selected it. The delay override and retry handlers of this policy receive a RetryContext for both exceptions and retried results.