Skip to content

Instantly share code, notes, and snippets.

@malteb247
Last active February 2, 2017 12:17
Show Gist options
  • Save malteb247/f1a250101bfe82252402801557780af8 to your computer and use it in GitHub Desktop.
Save malteb247/f1a250101bfe82252402801557780af8 to your computer and use it in GitHub Desktop.
Simple helper to implement retry logic
using System;
using System.Collections.Generic;
using System.Threading;
/// <summary>
/// Simple helper to implement retry logic
/// </summary>
/// <example>
/// // Retry 5 times with a break of 30 seconds.
/// Retry.Do(() => MyMethod(), TimeSpan.FromSeconds(30), 5)
/// </example>
/// <remarks>
/// Original source:
/// LBuschkin on Oct 13 '09
/// http://stackoverflow.com/a/1563234/3451056
/// </remarks>
public static class Retry
{
public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, retryCount);
}
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (var retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 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