Skip to content

Instantly share code, notes, and snippets.

@kpol
Created March 9, 2021 23:28
Show Gist options
  • Save kpol/4e85caa29a4edb04a6348cfb04c683e8 to your computer and use it in GitHub Desktop.
Save kpol/4e85caa29a4edb04a6348cfb04c683e8 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
namespace RetryPolicies
{
internal sealed class ExponentialRetryPolicy
{
public TimeSpan InitialDelay { get; set; } = TimeSpan.FromSeconds(10);
public int NumberOfRetries{ get; set; } = 5;
public async Task<T> OperationWithBasicRetryAsync<T>(Func<Task<T>> operation)
{
int currentRetry = 0;
var delay = (int)InitialDelay.TotalMilliseconds;
T result;
while (true)
{
try
{
result = await operation();
break;
}
catch
{
currentRetry++;
if (currentRetry > NumberOfRetries)
{
throw;
}
}
await Task.Delay(delay);
delay *= 2;
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment