Skip to content

Instantly share code, notes, and snippets.

@FusRoDah061
Created July 20, 2019 16:28
Show Gist options
  • Save FusRoDah061/9ef3f0b58f4220c9d89ef99b5aa67b4c to your computer and use it in GitHub Desktop.
Save FusRoDah061/9ef3f0b58f4220c9d89ef99b5aa67b4c to your computer and use it in GitHub Desktop.
/*
https://stackoverflow.com/questions/1563191/cleanest-way-to-write-retry-logic/1563234?fbclid=IwAR1xkK60U07JQP8NZ0h61mWuF21AOWEfGXLrDs94PuvLI0xo7HMkdsWSQcs#1563234
Usage:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
Or
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));
Or
int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);
*/
public static class Retry
{
public static void Do(
Action action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, maxAttemptCount);
}
public static T Do<T>(
Func<T> action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
var exceptions = new List<Exception>();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
Thread.Sleep(retryInterval);
}
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment