Skip to content

Add CancellationToken Support for Retry #877

Description

@blatybus

Retry does not support CancellationToken at the moment. Something like this would be nice to have so that retries can be cancelled:

public static TResult Retry(
Func<CancellationToken, TResult> producer,
Func<Exception, bool> shouldRetry,
IRetryPolicy retryPolicy,
CancellationToken cancellationToken = default)
{
var retryCount = 0;

while (true)
{
    cancellationToken.ThrowIfCancellationRequested();

    try
    {
        return producer(cancellationToken);
    }
    catch (Exception exception)
        when (shouldRetry(exception) && retryCount < retryPolicy.MaxRetries)
    {
        retryCount++;

        Task.Delay(retryPolicy.Delay(retryCount), cancellationToken)
            .GetAwaiter()
            .GetResult();
    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions