Skip to content

Instantly share code, notes, and snippets.

@FusRoDah061
Created July 20, 2019 16:28

Revisions

  1. FusRoDah061 created this gist Jul 20, 2019.
    50 changes: 50 additions & 0 deletions retry.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    /*
    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);
    }
    }