Async retry helper with capped exponential backoff
C#
using System;
using System.Threading.Tasks;
static async Task<T> RetryAsync<T>(Func<Task<T>> action, int maxTries = 5,
int baseMs = 200, int capMs = 5000)
{
var rnd = new Random();
for (int attempt = 1; ; attempt++)
{
try { return await action(); }
catch (Exception) when (attempt < maxTries)
{
double window = Math.Min(capMs, baseMs * Math.Pow(2, attempt - 1));
await Task.Delay((int)(window / 2 + rnd.NextDouble() * window / 2));
}
}
}