RetryStrategyExtensions Class

Namespace
Kampute.Resilience
Assembly
  • Kampute.Resilience.dll

Definition

Provides extension methods for IRetryStrategy to limit its retries, cap and spread its delays, create retry policies, start sessions, and run operations with retries.
public static class RetryStrategyExtensions
Inheritance

Methods

Execute(this IRetryStrategy, Action<CancellationToken>, CancellationToken)

Runs a blocking operation and retries it as the strategy decides when it throws an exception.
public static void Execute(this IRetryStrategy strategy, Action<CancellationToken> operation, CancellationToken cancellationToken = default)

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or 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; a wait ends as soon as cancellationToken is canceled. Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. To retry only selected exceptions, start a policy with RetryOn<TException>(this IRetryStrategy).

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

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

Runs a blocking operation that returns a value and retries it as the strategy decides when it throws an exception.
public static T Execute<T>(this IRetryStrategy strategy, Func<CancellationToken, T> operation, CancellationToken cancellationToken = default)

Type Parameters

T
The type of the value the operation returns.

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or 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; a wait ends as soon as cancellationToken is canceled. Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. To retry only selected exceptions, start a policy with RetryOn<TException>(this IRetryStrategy).

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

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

Runs a blocking operation that receives a state, and retries it as the strategy decides when it throws an exception.
public static void Execute<TState>(this 
	IRetryStrategy strategy,
	TState state,
	Action<TState, CancellationToken> operation,
	CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or 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. Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. When 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>(this IRetryStrategy, TState, Func<TState, CancellationToken, T>, CancellationToken)

Runs a blocking operation that receives a state and returns a value, and retries it as the strategy decides when it throws an exception.
public static T Execute<TState, T>(this 
	IRetryStrategy strategy,
	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

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or 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. Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. When 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(this IRetryStrategy, Func<CancellationToken, Task>, CancellationToken)

Runs an asynchronous operation and retries it as the strategy decides when it throws an exception.
public static Task ExecuteAsync(this IRetryStrategy strategy, Func<CancellationToken, Task> operation, CancellationToken cancellationToken = default)

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. To retry only selected exceptions, start a policy with RetryOn<TException>(this IRetryStrategy).

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

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

Runs an asynchronous operation that returns a value and retries it as the strategy decides when it throws an exception.
public static Task<T> ExecuteAsync<T>(this IRetryStrategy strategy, Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken = default)

Type Parameters

T
The type of the value the operation returns.

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. To retry only selected exceptions, start a policy with RetryOn<TException>(this IRetryStrategy).

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

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

Runs an asynchronous operation that receives a state, and retries it as the strategy decides when it throws an exception.
public static Task ExecuteAsync<TState>(this 
	IRetryStrategy strategy,
	TState state,
	Func<TState, CancellationToken, Task> operation,
	CancellationToken cancellationToken = default)

Type Parameters

TState
The type of the state passed to the operation.

Parameters

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. When 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>(this IRetryStrategy, TState, Func<TState, CancellationToken, Task<T>>, CancellationToken)

Runs an asynchronous operation that receives a state and returns a value, and retries it as the strategy decides when it throws an exception.
public static Task<T> ExecuteAsync<TState, T>(this 
	IRetryStrategy strategy,
	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

strategy IRetryStrategy
The retry strategy that decides whether and when to retry.
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 strategy or operation is null.
OperationCanceledException
Thrown if cancellationToken is canceled while waiting before a retry.

Remarks

Every exception is retried except an OperationCanceledException thrown after cancellationToken has been canceled. When 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(this IRetryStrategy, Action<RetryContext>)

Creates a retry policy that retries every exception and invokes a handler for each approved retry.
public static RetryPolicy OnRetry(this IRetryStrategy strategy, Action<RetryContext> handler)

Parameters

strategy IRetryStrategy
The strategy that decides whether and when to retry.
handler Action<RetryContext>
The handler, which receives the failed attempt and the delay that execution waits before the retry.

Returns

RetryPolicy
A new RetryPolicy.

Exceptions

ArgumentNullException
Thrown if strategy or handler is null.

Remarks

See RetryPolicy.OnRetry(Action<RetryContext>) for when the handler runs.

OverrideDelay(this IRetryStrategy, Func<RetryContext, TimeSpan>)

Creates a retry policy that retries every exception, replacing the strategy's delay with one computed from the failed attempt.
public static RetryPolicy OverrideDelay(this IRetryStrategy strategy, Func<RetryContext, TimeSpan> delay)

Parameters

strategy IRetryStrategy
The strategy that decides whether to retry and proposes the delay.
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.

Returns

RetryPolicy
A new RetryPolicy.

Exceptions

ArgumentNullException
Thrown if strategy or delay is null.

Remarks

RetryOn(this IRetryStrategy, Func<Exception, bool>)

Creates a retry policy that retries the exceptions that satisfy a condition, as the strategy decides.
public static RetryPolicy RetryOn(this IRetryStrategy strategy, Func<Exception, bool> predicate)

Parameters

strategy IRetryStrategy
The strategy that decides whether and when to retry.
predicate Func<Exception, bool>
A function that returns true for the exceptions to retry.

Returns

RetryPolicy
A new RetryPolicy that retries only the exceptions that predicate selects.

Exceptions

ArgumentNullException
Thrown if strategy or predicate is null.

Remarks

Chain further RetryOn calls to retry other exceptions as well.

RetryOn<TException>(this IRetryStrategy)

Creates a retry policy that retries the exceptions of the specified type as the strategy decides.
public static RetryPolicy RetryOn<TException>(this IRetryStrategy strategy)
	where TException : Exception

Type Parameters

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

Parameters

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

Returns

RetryPolicy
A new RetryPolicy that retries only the exceptions of type TException.

Exceptions

ArgumentNullException
Thrown if strategy is null.

Remarks

Chain further RetryOn calls to retry other exceptions as well.

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

Creates a retry policy that retries the exceptions of the specified type that satisfy a condition, as the strategy decides.
public static RetryPolicy RetryOn<TException>(this IRetryStrategy strategy, Func<TException, bool> predicate)
	where TException : Exception

Type Parameters

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

Parameters

strategy IRetryStrategy
The strategy that decides whether and when to retry.
predicate Func<TException, bool>
A function that returns true for the exceptions of type TException to retry.

Returns

RetryPolicy
A new RetryPolicy that retries only the exceptions that predicate selects.

Exceptions

ArgumentNullException
Thrown if strategy or predicate is null.

Remarks

Chain further RetryOn calls to retry other exceptions as well.

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

Creates a retry policy for operations returning T that retries every exception and the results that satisfy a condition, as the strategy decides.
public static RetryPolicy<T> RetryOnResult<T>(this IRetryStrategy strategy, Func<T, bool> predicate)

Type Parameters

T
The type returned by the operations the policy runs.

Parameters

strategy IRetryStrategy
The strategy that decides whether and when to retry.
predicate Func<T, bool>
A function that returns true for the results to retry.

Returns

RetryPolicy<T>
A new RetryPolicy<T>.

Exceptions

ArgumentNullException
Thrown if strategy or predicate is null.

Remarks

Chain RetryOn calls to retry only selected exceptions.

StartSession(this IRetryStrategy)

Starts a retry session for one operation that the strategy governs.
public static RetrySession StartSession(this IRetryStrategy strategy)

Parameters

strategy IRetryStrategy
The retry strategy of the session.

Returns

RetrySession
A new RetrySession, with no retries and its elapsed time starting now.

Exceptions

ArgumentNullException
Thrown if strategy is null.

WithJitter(this IRetryStrategy, double)

Adds random jitter to the delays of a retry strategy.
public static JitterModifier WithJitter(this IRetryStrategy strategy, double jitterFactor = 0.5)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
jitterFactor double optional
The largest proportion of each delay, between 0 and 1, by which the delay is randomly lengthened or shortened (optional). The default is 0.5.

Returns

JitterModifier
A JitterModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.
ArgumentOutOfRangeException
Thrown if jitterFactor is not between 0 and 1.

WithMaxDelay(this IRetryStrategy, TimeSpan)

Caps each delay of a retry strategy.
public static MaxDelayModifier WithMaxDelay(this IRetryStrategy strategy, TimeSpan maxDelay)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
maxDelay TimeSpan
The longest delay before a retry. Longer delays of strategy are shortened to it.

Returns

MaxDelayModifier
A MaxDelayModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.
ArgumentOutOfRangeException
Thrown if maxDelay is negative.

Remarks

The cap does not limit the number of retries. Its position relative to WithJitter(this IRetryStrategy, double) matters: jitter added after the cap spreads the capped delays, so they can exceed maxDelay by the jitter factor; jitter added before the cap keeps every delay within maxDelay.

WithMaxDelay(this IRetryStrategy, int)

Caps each delay of a retry strategy at a number of milliseconds.
public static MaxDelayModifier WithMaxDelay(this IRetryStrategy strategy, int millisecondsMaxDelay)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
millisecondsMaxDelay int
The longest delay before a retry, in milliseconds. Longer delays of strategy are shortened to it.

Returns

MaxDelayModifier
A MaxDelayModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.
ArgumentOutOfRangeException
Thrown if millisecondsMaxDelay is negative.

Remarks

The cap does not limit the number of retries. Its position relative to WithJitter(this IRetryStrategy, double) matters: jitter added after the cap spreads the capped delays, so they can exceed the cap by the jitter factor; jitter added before the cap keeps every delay within it.

WithMaxElapsedTime(this IRetryStrategy, TimeSpan)

Limits the time during which a retry strategy allows retries.
public static MaxElapsedTimeModifier WithMaxElapsedTime(this IRetryStrategy strategy, TimeSpan maxElapsedTime)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
maxElapsedTime TimeSpan
The time since the start of retry attempts after which no further retry is allowed. A delay that would end after it is shortened to end at it.

Returns

MaxElapsedTimeModifier
A MaxElapsedTimeModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.
ArgumentOutOfRangeException
Thrown if maxElapsedTime is negative.

Remarks

The limit applies to the decision to retry, not to the operation: an operation that is running when the limit is reached is not canceled.

WithMaxElapsedTime(this IRetryStrategy, int)

Limits the time, in milliseconds, during which a retry strategy allows retries.
public static MaxElapsedTimeModifier WithMaxElapsedTime(this IRetryStrategy strategy, int millisecondsMaxElapsedTime)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
millisecondsMaxElapsedTime int
The number of milliseconds since the start of retry attempts after which no further retry is allowed. A delay that would end after it is shortened to end at it.

Returns

MaxElapsedTimeModifier
A MaxElapsedTimeModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.
ArgumentOutOfRangeException
Thrown if millisecondsMaxElapsedTime is negative.

Remarks

The limit applies to the decision to retry, not to the operation: an operation that is running when the limit is reached is not canceled.

WithMaxRetries(this IRetryStrategy, uint)

Limits the number of retries a retry strategy allows.
public static MaxRetriesModifier WithMaxRetries(this IRetryStrategy strategy, uint maxRetries)

Parameters

strategy IRetryStrategy
The retry strategy to modify.
maxRetries uint
The maximum number of retries after the initial attempt. Zero allows no retry.

Returns

MaxRetriesModifier
A MaxRetriesModifier that wraps strategy.

Exceptions

ArgumentNullException
Thrown if strategy is null.