A Simple Retry Helper for Retrying Asynchronous Operations

Today I wanted to share a simple helper that I use when I need a retry mechanism for asynchronous calls. Here is how you would use it:

public async Task Foo()
{
    var data = await AsyncRetry.DoAsync(GetDataAsync);
 
    // Do something with the data
}
 
public Task GetDataAsync()
{
    return Task.FromResult("Hello, world!");
}

Or a more complicated usage scenario with cancellation support and custom settings for retry interval, retry count and on what exceptions to retry:

public async Task Foo(CancellationToken cancellationToken)
{
    var retryPolicy = new AsyncRetryPolicy(
        retryInterval: TimeSpan.FromSeconds(5),
        retryCount: 5,
        exceptionFilter: ex => ex is TimeoutException);
 
    var data = await AsyncRetry.DoAsync(
            () => GetDataAsync(cancellationToken), 
            retryPolicy, 
            cancellationToken);
 
    // Do something with the data
}
 
public Task GetDataAsync(CancellationToken cancellationToken)
{
    return Task.Run(() => "Hello, world!", cancellationToken);
}

In the example above we retry the operation 5 times, with 5 second interval and only when a TimeoutException occurs.
Here is a with the full source code the helper:

Pavlo Glazkov

Pavlo Glazkov

Programmer. Full stack, with a focus on UI. JavaScript/TypeScript, Angular, Node.js, .NET

Read More