548

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
    break; // success!
  } catch {
    if(--retries == 0) throw;
    else Thread.Sleep(1000);
  }
}

I would like to rewrite this in a general retry function like:

TryThreeTimes(DoSomething);

Is it possible in C#? What would be the code for the TryThreeTimes() method?

4
  • 1
    A simple cycle is not enough? Why just not to iterate over and execute logic for several times?
    – Restuta
    Commented Oct 13, 2009 at 22:08
  • 13
    Personally, I would be extremely wary of any such helper method. It's certainly possible to implement using lambdas, but the pattern itself is extremely smelly, so introducing a helper for it (which implies that it is frequently repeated) is in and of itself highly suspicious, and strongly hints at bad overall design. Commented Oct 13, 2009 at 22:53
  • 14
    In my case, my DoSomething()s are doing stuff on remote machines such as deleting files, or trying to hit a network port. In both cases, there are major timing issues for when DoSomething will succeed and because of the remoteness, there is no event I can listen on. So yeah, its smelly. Suggestions welcome.
    – noctonura
    Commented Oct 13, 2009 at 22:58
  • 27
    @PavelMinaev why would using retries hint at bad overall design? If you write a lot of code that connects integration points then using retries is definitely a pattern you should seriously consider using.
    – bytedev
    Commented Aug 23, 2016 at 16:32

32 Answers 32

646

Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:

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);
    }
}

You can now use this utility method to perform retry logic:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

or:

Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));

or:

int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);

Or you could even make an async overload.

23
  • 7
    +1, especially for the warning and error-checking. I'd be more comfortable if this passed in the type of the exception to catch as a generic parameter (where T: Exception), though.
    – TrueWill
    Commented Oct 13, 2009 at 22:55
  • 2
    It was my intent that "retries" actually meant retries. But it's not too hard to change it to mean "tries". As long as the name is kept meaningful. There are other opportunities to improve the code, like checking for negative retries, or negative timeouts - for example. I omitted these mostly to keep the example simple ... but again, in practice these would probably be good enhancements to the implementation.
    – LBushkin
    Commented Oct 14, 2009 at 0:05
  • 60
    We use a similar pattern for our DB access in a high volume Biztalk App, but with two improvements: We have blacklists for exceptions that shouldn't be retried and we store the first exception that occurs and throw that when the retry ultimately fails. Reason being that the second and following exceptions often are different from the first one. In that case you hide the initial problem when rethrowing only the last exception.
    – TToni
    Commented Mar 22, 2012 at 11:21
  • 3
    @Dexters We throw a new exception with the original exception as inner exception. The original stack trace is available as attribute from the inner exceptions.
    – TToni
    Commented Mar 31, 2013 at 21:31
  • 10
    You could also try using an open source library such as Polly to handle this. There is much more flexibility for waiting between retries and it has been validated by many others that have used the project. Example: Policy.Handle<DivideByZeroException>().WaitAndRetry(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3) }); Commented Aug 25, 2015 at 2:28
283

You should try Polly. It's a .NET library written by me that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

Example

Policy
    .Handle<SqlException>(ex => ex.Number == 1205)
    .Or<ArgumentException>(ex => ex.ParamName == "example")
    .WaitAndRetry(3, _ => TimeSpan.FromSeconds(3))
    .Execute(DoSomething);
5
  • 3
    What is actually the OnRetry delegate? I assume it is what we need to perform when exception is occurred. So when exception is occurred OnRetry delegate will call and afterwards Execute delegate. Is it so? Commented May 9, 2018 at 9:44
  • Where I should use this snippet code? if the answer is startup.cs, how to register Policy?
    – Sina Riani
    Commented Jun 1, 2021 at 9:43
  • Q: What is actually the OnRetry delegate? A: It only allows you to do something when a retry is performed (e.g., log something). You don't need to call Execute in there, that happens automatically.
    – D.R.
    Commented Jan 4, 2022 at 15:08
  • @SinaRiani You can do something like this with Polly. stackoverflow.com/a/68013076/4267686 Commented May 11, 2022 at 21:02
  • does it work in Azure Functions? If yes, how?
    – sam
    Commented Jun 21 at 7:07
78
public void TryThreeTimes(Action action)
{
    var tries = 3;
    while (true) {
        try {
            action();
            break; // success!
        } catch {
            if (--tries == 0)
                throw;
            Thread.Sleep(1000);
        }
    }
}

Then you would call:

TryThreeTimes(DoSomething);

...or alternatively...

TryThreeTimes(() => DoSomethingElse(withLocalVariable));

A more flexible option:

public void DoWithRetry(Action action, TimeSpan sleepPeriod, int tryCount = 3)
{
    if (tryCount <= 0)
        throw new ArgumentOutOfRangeException(nameof(tryCount));

    while (true) {
        try {
            action();
            break; // success!
        } catch {
            if (--tryCount == 0)
                throw;
            Thread.Sleep(sleepPeriod);
        }
   }
}

To be used as:

DoWithRetry(DoSomething, TimeSpan.FromSeconds(2), tryCount: 10);

A more modern version with support for async/await:

public async Task DoWithRetryAsync(Func<Task> action, TimeSpan sleepPeriod, int tryCount = 3)
{
    if (tryCount <= 0)
        throw new ArgumentOutOfRangeException(nameof(tryCount));

    while (true) {
        try {
            await action();
            return; // success!
        } catch {
            if (--tryCount == 0)
                throw;
            await Task.Delay(sleepPeriod);
        }
   }
}

To be used as:

await DoWithRetryAsync(DoSomethingAsync, TimeSpan.FromSeconds(2), tryCount: 10);
6
  • 2
    preferably change the if to: --retryCount <= 0 because this will go on forever if you want to disable retries by setting it to 0. Technically the term retryCount isn't a really good name, because it won't retry if you set it to 1. either rename it to tryCount or put the -- behind.
    – Stefanvds
    Commented May 31, 2016 at 6:47
  • 2
    @saille I agree. However the OP (and all other answers) are using Thread.Sleep. Alternatives are to use timers, or more likely nowadays to use async to retry, with Task.Delay. Commented Oct 4, 2017 at 10:22
  • 4
    I've added an async version. Commented Oct 4, 2017 at 10:26
  • Only break if action returns true ? Func<bool>
    – Kiquenet
    Commented Apr 18, 2018 at 14:08
  • 1
    @ibda you'd only use the async version if you want to free the thread up to do other work, rather than sleeping. If you run work on the thread pool, for example, you shouldn't be putting those threads to sleep. Commented Feb 2, 2022 at 20:41
58

This is possibly a bad idea. First, it is emblematic of the maxim "the definition of insanity is doing the same thing twice and expecting different results each time". Second, this coding pattern does not compose well with itself. For example:

Suppose your network hardware layer resends a packet three times on failure, waiting, say, a second between failures.

Now suppose the software layer resends a notification about a failure three times on packet failure.

Now suppose the notification layer reactivates the notification three times on a notification delivery failure.

Now suppose the error reporting layer reactivates the notification layer three times on a notification failure.

And now suppose the web server reactivates the error reporting three times on error failure.

And now suppose the web client resends the request three times upon getting an error from the server.

Now suppose the line on the network switch that is supposed to route the notification to the administrator is unplugged. When does the user of the web client finally get their error message? I make it at about twelve minutes later.

Lest you think this is just a silly example: we have seen this bug in customer code, though far, far worse than I've described here. In the particular customer code, the gap between the error condition happening and it finally being reported to the user was several weeks because so many layers were automatically retrying with waits. Just imagine what would happen if there were ten retries instead of three.

Usually the right thing to do with an error condition is report it immediately and let the user decide what to do. If the user wants to create a policy of automatic retries, let them create that policy at the appropriate level in the software abstraction.

22
  • 19
    +1. Raymond shares a real life example here, blogs.msdn.com/oldnewthing/archive/2005/11/07/489807.aspx Commented Oct 14, 2009 at 13:57
  • 246
    -1 This advice is useless for transient network failures encountered by automated batch processing systems.
    – nohat
    Commented Sep 24, 2010 at 21:22
  • 17
    Not sure if this is saying "Don't do it" followed by "do it". Most of the people asking this question are probably the people working in the software abstraction.
    – Jim L
    Commented Apr 12, 2012 at 16:30
  • 57
    When you have long running batch jobs that use network resources, such as web services, you can't expect the network to be 100% reliable. There are going to be occasional timeouts, socket disconnects, possibly even spurious routing glitches or server outages that occur while you are using it. One option is to fail, but that may mean restarting a lengthy job later. Another option is to retry a few times with suitable delay to see if it's a temporary problem, then fail. I agree about composition, which you have to be aware of.. but it's sometimes the best choice. Commented Feb 4, 2013 at 22:13
  • 24
    I think that the quote you used at the beginning of your answer is interesting. "Expecting different results" is only insanity if prior experience regularly gives you the same results. While software is built on a promise of consistency, there are definitely circumstances where we are required to interact with unreliable forces outside of our control. Commented May 21, 2014 at 13:50
34

The Transient Fault Handling Application Block provides an extensible collection of retry strategies including:

  • Incremental
  • Fixed interval
  • Exponential back-off

It also includes a collection of error detection strategies for cloud-based services.

For more information see this chapter of the Developer's Guide.

Available via NuGet (search for 'topaz').

6
  • 2
    Interesting. Can you use this outside of Windows Azure, say in a Winforms app? Commented Jan 22, 2013 at 5:18
  • 7
    Absolutely. Use the core retry mechanism and provide your own detection strategies. We intentionally decoupled those. Find the core nuget package here: nuget.org/packages/TransientFaultHandling.Core Commented Jan 22, 2013 at 15:13
  • 2
    Also, the project is now under Apache 2.0 and accepting community contributions. aka.ms/entlibopen Commented Dec 3, 2013 at 0:50
  • 1
    @Alex. The pieces of it are making it into the platform. Commented Apr 14, 2015 at 16:15
  • 3
    This is now deprecated, and last I used it it contained some bugs that as far as I know weren't, and never will be fixed: github.com/MicrosoftArchive/…. Commented Aug 22, 2017 at 14:12
18

I'm a fan of recursion and extension methods, so here are my two cents:

public static void InvokeWithRetries(this Action @this, ushort numberOfRetries)
{
    try
    {
        @this();
    }
    catch
    {
        if (numberOfRetries == 0)
            throw;

        InvokeWithRetries(@this, --numberOfRetries);
    }
}
15

Allowing for functions and retry messages

public static T RetryMethod<T>(Func<T> method, int numRetries, int retryTimeout, Action onFailureAction)
{
 Guard.IsNotNull(method, "method");            
 T retval = default(T);
 do
 {
   try
   {
     retval = method();
     return retval;
   }
   catch
   {
     onFailureAction();
      if (numRetries <= 0) throw; // improved to avoid silent failure
      Thread.Sleep(retryTimeout);
   }
} while (numRetries-- > 0);
  return retval;
}
2
14

You might also consider adding the exception type you want to retry for. For instance is this a timeout exception you want to retry? A database exception?

RetryForExcpetionType(DoSomething, typeof(TimeoutException), 5, 1000);

public static void RetryForExcpetionType(Action action, Type retryOnExceptionType, int numRetries, int retryTimeout)
{
    if (action == null)
        throw new ArgumentNullException("action");
    if (retryOnExceptionType == null)
        throw new ArgumentNullException("retryOnExceptionType");
    while (true)
    {
        try
        {
            action();
            return;
        }
        catch(Exception e)
        {
            if (--numRetries <= 0 || !retryOnExceptionType.IsAssignableFrom(e.GetType()))
                throw;

            if (retryTimeout > 0)
                System.Threading.Thread.Sleep(retryTimeout);
        }
    }
}

You might also note that all of the other examples have a similar issue with testing for retries == 0 and either retry infinity or fail to raise exceptions when given a negative value. Also Sleep(-1000) will fail in the catch blocks above. Depends on how 'silly' you expect people to be but defensive programming never hurts.

6
  • 10
    +1, but why not do RetryForException<T>(...) where T: Exception, then catch(T e)? Just tried it and it works perfectly.
    – TrueWill
    Commented Oct 14, 2009 at 1:23
  • Either or here since I don't need to do anything with the Type provided I figured a plain old parameter would do the trick. Commented Oct 14, 2009 at 1:49
  • @TrueWill apparently catch(T ex) has some bugs according to this post stackoverflow.com/questions/1577760/… Commented Oct 16, 2009 at 14:15
  • 3
    Update: Actually a better implementation I've been using takes a Predicate<Exception> delegate that returns true if a retry is appropriate. This allows you to use native error codes or other properties of the exception to determine if a retry is applicable. For instance HTTP 503 codes. Commented Apr 16, 2012 at 18:44
  • 1
    "Also Sleep(-1000) will fail in the catch blocks above" ... use a TimeSpan and you won't get this problem. Plus TimeSpan is much more flexible and self descriptive. From your signature of "int retryTimeout" how do i know if retryTimeout is MS, seconds, minutes, years?? ;-)
    – bytedev
    Commented Aug 24, 2016 at 10:23
12

Implemented LBushkin's answer in the latest fashion:

    public static async Task Do(Func<Task> task, TimeSpan retryInterval, int maxAttemptCount = 3)
    {
        var exceptions = new List<Exception>();
        for (int attempted = 0; attempted < maxAttemptCount; attempted++)
        {
            try
            {
                if (attempted > 0)
                {
                    await Task.Delay(retryInterval);
                }

                await task();
                return;
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }
        throw new AggregateException(exceptions);
    }

    public static async Task<T> Do<T>(Func<Task<T>> task, TimeSpan retryInterval, int maxAttemptCount = 3)
    {
        var exceptions = new List<Exception>();
        for (int attempted = 0; attempted < maxAttemptCount; attempted++)
        {
            try
            {
                if (attempted > 0)
                {
                    await Task.Delay(retryInterval);
                }
                return await task();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }
        throw new AggregateException(exceptions);
    }  

and to use it:

await Retry.Do([TaskFunction], retryInterval, retryAttempts);

whereas the function [TaskFunction] can either be Task<T> or just Task.

2
  • 1
    Thank you, Fabian! This should be upvoted all the way to the top!
    – JamesHoux
    Commented Jul 31, 2018 at 20:56
  • 1
    @MarkLauter the short answer is yes. ;-) Commented Sep 29, 2018 at 14:17
9

Use Polly

https://github.com/App-vNext/Polly-Samples

Here is a retry-generic I use with Polly

public T Retry<T>(Func<T> action, int retryCount = 0)
{
    PolicyResult<T> policyResult = Policy
     .Handle<Exception>()
     .Retry(retryCount)
     .ExecuteAndCapture<T>(action);

    if (policyResult.Outcome == OutcomeType.Failure)
    {
        throw policyResult.FinalException;
    }

    return policyResult.Result;
}

Use it like this

var result = Retry(() => MyFunction()), 3);
1
9

Keep it simple with C# 6.0

public async Task<T> Retry<T>(Func<T> action, TimeSpan retryInterval, int retryCount)
{
    try
    {
        return action();
    }
    catch when (retryCount != 0)
    {
        await Task.Delay(retryInterval);
        return await Retry(action, retryInterval, --retryCount);
    }
}
1
  • 4
    I am kind of curious, would this spawn an insane amount of threads with a high retry count and interval because of returning the same awaitable method?
    – HuntK24
    Commented Jun 15, 2017 at 22:37
7

Building on the previous work, I thought about enhancing the retry logic in three ways:

  1. Specifying what exception type to catch/retry. This is the primary enhacement as retrying for any exception is just plain wrong.
  2. Not nesting the last try in a try/catch, achieving slightly better performance
  3. Making it an Action extension method

    static class ActionExtensions
    {
      public static void InvokeAndRetryOnException<T> (this Action action, int retries, TimeSpan retryDelay) where T : Exception
      {
        if (action == null)
          throw new ArgumentNullException("action");
    
        while( retries-- > 0 )
        {
          try
          {
            action( );
            return;
          }
          catch (T)
          {
            Thread.Sleep( retryDelay );
          }
        }
    
        action( );
      }
    }
    

The method can then be invoked like so (anonymous methods can be used as well, of course):

new Action( AMethodThatMightThrowIntermittentException )
  .InvokeAndRetryOnException<IntermittentException>( 2, TimeSpan.FromSeconds( 1 ) );
1
  • 1
    This is excellent. But personally I wouldn't call it 'retryTimeout' as it's not really a Timeout. 'RetryDelay', perhaps?
    – Holf
    Commented Jun 10, 2015 at 11:17
5

I have two implementations of this pattern using Polly. One is async.

My synchronous method is based on this answer by Erik Bergstedt

public static T Retry<T>(Func<T> action, TimeSpan retryWait, int retryCount = 0)
{
    PolicyResult<T> policyResult = Policy
        .Handle<ApiException>(ex => ex.ResponseCode == (int)HttpStatusCode.TooManyRequests)
        .WaitAndRetry(retryCount, retryAttempt => retryWait)
        .ExecuteAndCapture(action);

    if (policyResult.Outcome == OutcomeType.Failure)
    {
        throw policyResult.FinalException;
    }

    return policyResult.Result;
}

Async:

public static async Task<T> RetryAsync<T>(Func<Task<T>> action, TimeSpan retryWait, int retryCount = 0)
{
    PolicyResult<T> policyResult = await Policy
        .Handle<ApiException>(ex => ex.ResponseCode == (int)HttpStatusCode.TooManyRequests)
        .WaitAndRetryAsync(retryCount, retryAttempt => retryWait)
        .ExecuteAndCaptureAsync(action);

    if (policyResult.Outcome == OutcomeType.Failure)
    {
        throw policyResult.FinalException;
    }

    return policyResult.Result;
}

It would also be easy to allow an exception type to be passed in as well as the lambda for the exception type.

4

I'd implement this:

public static bool Retry(int maxRetries, Func<bool, bool> method)
{
    while (maxRetries > 0)
    {
        if (method(maxRetries == 1))
        {
            return true;
        }
        maxRetries--;
    }
    return false;        
}

I wouldn't use exceptions the way they're used in the other examples. It seems to me that if we're expecting the possibility that a method won't succeed, its failure isn't an exception. So the method I'm calling should return true if it succeeded, and false if it failed.

Why is it a Func<bool, bool> and not just a Func<bool>? So that if I want a method to be able to throw an exception on failure, I have a way of informing it that this is the last try.

So I might use it with code like:

Retry(5, delegate(bool lastIteration)
   {
       // do stuff
       if (!succeeded && lastIteration)
       {
          throw new InvalidOperationException(...)
       }
       return succeeded;
   });

or

if (!Retry(5, delegate(bool lastIteration)
   {
       // do stuff
       return succeeded;
   }))
{
   Console.WriteLine("Well, that didn't work.");
}

If passing a parameter that the method doesn't use proves to be awkward, it's trivial to implement an overload of Retry that just takes a Func<bool> as well.

5
  • 1
    +1 for avoiding the exception. Though I'd do a void Retry(...) and throw something? Boolean returns and/or return codes are too often overlooked. Commented Oct 13, 2009 at 23:22
  • 2
    "if we're expecting the possibility that a method won't succeed, its failure isn't an exception" - while that's true in some cases, exception need not imply exceptional. It's for error handling. There is no guarantee that the caller will check a Boolean result. There is a guarantee that an exception will be handled (by the runtime shutting down the application if nothing else does).
    – TrueWill
    Commented Oct 14, 2009 at 1:17
  • I can't find the reference but I believe .NET defines an Exception as "a method didn't do what it said it will do". 1 purpose is to use exceptions to indicate a problem rather than the Win32 pattern of requiring the caller to check the return value if the function succeeded or not.
    – noctonura
    Commented Oct 14, 2009 at 4:03
  • But exceptions don't merely "indicate a problem." They also include a mass of diagnostic information that costs time and memory to compile. There are clearly situations in which that doesn't matter the least little bit. But there are a lot where it does. .NET doesn't use exceptions for control flow (compare, say, with Python's use of the StopIteration exception), and there's a reason. Commented Oct 14, 2009 at 8:56
  • The TryDo method pattern is a slippery slope. Before you know it, your entire call stack will consist of TryDo methods. Exceptions were invented to avoid such a mess.
    – HappyNomad
    Commented Feb 1, 2020 at 16:59
4

Update after 6 years: now I consider that the approach below is pretty bad. To create a retry logic we should consider to use a library like Polly.


My async implementation of the retry method:

public static async Task<T> DoAsync<T>(Func<dynamic> action, TimeSpan retryInterval, int retryCount = 3)
    {
        var exceptions = new List<Exception>();

        for (int retry = 0; retry < retryCount; retry++)
        {
            try
            {
                return await action().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }

            await Task.Delay(retryInterval).ConfigureAwait(false);
        }
        throw new AggregateException(exceptions);
    }

Key points: I used .ConfigureAwait(false); and Func<dynamic> instead Func<T>

4
  • 1
    This does not provide an answer to the question. Please consider posting your answer as a new question, using the "Ask Question" button at the top of the page, then posting your own answer to the question to share what you learned with the community.
    – elixenide
    Commented Mar 7, 2014 at 5:47
  • Much simpler with C# 5.0 than codereview.stackexchange.com/q/55983/54000 but maybe CansellactionToken should be injected.
    – SerG
    Commented Dec 11, 2014 at 10:32
  • 2
    There's a problem with this implementation. After the final retry, right before giving up, Task.Delay is called for no reason.
    – HappyNomad
    Commented Feb 1, 2020 at 16:04
  • 1
    @HappyNomad this is a 6 years old answer and now I consider that its a pretty bad approach to create a retry logic :)) thanks for notification. I will update my answer according to that consideration. Commented Feb 2, 2020 at 8:59
3

I needed a method that supports cancellation, while I was at it, I added support for returning intermediate failures.

public static class ThreadUtils
{
    public static RetryResult Retry(
        Action target,
        CancellationToken cancellationToken,
        int timeout = 5000,
        int retries = 0)
    {
        CheckRetryParameters(timeout, retries)
        var failures = new List<Exception>();
        while(!cancellationToken.IsCancellationRequested)
        {
            try
            {
                target();
                return new RetryResult(failures);
            }
            catch (Exception ex)
            {
                failures.Add(ex);
            }

            if (retries > 0)
            {
                retries--;
                if (retries == 0)
                {
                    throw new AggregateException(
                     "Retry limit reached, see InnerExceptions for details.",
                     failures);
                }
            }

            if (cancellationToken.WaitHandle.WaitOne(timeout))
            {
                break;
            }
        }

        failures.Add(new OperationCancelledException(
            "The Retry Operation was cancelled."));
        throw new AggregateException("Retry was cancelled.", failures);
    }

    private static void CheckRetryParameters(int timeout, int retries)
    {
        if (timeout < 1)
        {
            throw new ArgumentOutOfRangeException(...
        }

        if (retries < 0)
        {
            throw new ArgumentOutOfRangeException(...

        }
    }

    public class RetryResult : IEnumerable<Exception>
    {
        private readonly IEnumerable<Exception> failureExceptions;
        private readonly int failureCount;

         protected internal RetryResult(
             ICollection<Exception> failureExceptions)
         {
             this.failureExceptions = failureExceptions;
             this.failureCount = failureExceptions.Count;
         }
    }

    public int FailureCount
    {
        get { return this.failureCount; }
    }

    public IEnumerator<Exception> GetEnumerator()
    {
        return this.failureExceptions.GetEnumerator();
    }

    System.Collections.IEnumerator 
        System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

You can use the Retry function like this, retry 3 times with a 10 second delay but without cancellation.

try
{
    var result = ThreadUtils.Retry(
        SomeAction, 
        CancellationToken.None,
        10000,
        3);

    // it worked
    result.FailureCount // but failed this many times first.
}
catch (AggregationException ex)
{
   // oops, 3 retries wasn't enough.
}

Or, retry eternally every five seconds, unless cancelled.

try
{
    var result = ThreadUtils.Retry(
        SomeAction, 
        someTokenSource.Token);

    // it worked
    result.FailureCount // but failed this many times first.
}
catch (AggregationException ex)
{
   // operation was cancelled before success.
}

As you can guess, In my source code I've overloaded the Retry function to support the differing delgate types I desire to use.

3

This method allows retries on certain exception types (throws others immediately).

public static void DoRetry(
    List<Type> retryOnExceptionTypes,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
{
    for (var i = 0; i < retryCount; ++i)
    {
        try
        {
            actionToTry();
            break;
        }
        catch (Exception ex)
        {
            // Retries exceeded
            // Throws on last iteration of loop
            if (i == retryCount - 1) throw;

            // Is type retryable?
            var exceptionType = ex.GetType();
            if (!retryOnExceptionTypes.Contains(exceptionType))
            {
                throw;
            }

            // Wait before retry
            Thread.Sleep(msWaitBeforeEachRety);
        }
    }
}
public static void DoRetry(
    Type retryOnExceptionType,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
        => DoRetry(new List<Type> {retryOnExceptionType}, actionToTry, retryCount, msWaitBeforeEachRety);

Example usage:

DoRetry(typeof(IOException), () => {
    using (var fs = new FileStream(requestedFilePath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(entryBytes, 0, entryBytes.Length);
    }
});
2

Exponential backoff is a good retry strategy than simply trying x number of times. You can use a library like Polly to implement it.

2
2

For those who want to have both the option to retry on any exception or explicitly set the exception type, use this:

public class RetryManager 
{
    public void Do(Action action, 
                    TimeSpan interval, 
                    int retries = 3)
    {
        Try<object, Exception>(() => {
            action();
            return null;
        }, interval, retries);
    }

    public T Do<T>(Func<T> action, 
                    TimeSpan interval, 
                    int retries = 3)
    {
        return Try<T, Exception>(
              action
            , interval
            , retries);
    }

    public T Do<E, T>(Func<T> action, 
                       TimeSpan interval, 
                       int retries = 3) where E : Exception
    {
        return Try<T, E>(
              action
            , interval
            , retries);
    }

    public void Do<E>(Action action, 
                       TimeSpan interval, 
                       int retries = 3) where E : Exception
    {
        Try<object, E>(() => {
            action();
            return null;
        }, interval, retries);
    }

    private T Try<T, E>(Func<T> action, 
                       TimeSpan interval, 
                       int retries = 3) where E : Exception
    {
        var exceptions = new List<E>();

        for (int retry = 0; retry < retries; retry++)
        {
            try
            {
                if (retry > 0)
                    Thread.Sleep(interval);
                return action();
            }
            catch (E ex)
            {
                exceptions.Add(ex);
            }
        }

        throw new AggregateException(exceptions);
    }
}
1

Here's an async/await version that aggregates exceptions and supports cancellation.

/// <seealso href="https://learn.microsoft.com/en-us/azure/architecture/patterns/retry"/>
protected static async Task<T> DoWithRetry<T>( Func<Task<T>> action, CancellationToken cancelToken, int maxRetries = 3 )
{
    var exceptions = new List<Exception>();

    for ( int retries = 0; !cancelToken.IsCancellationRequested; retries++ )
        try {
            return await action().ConfigureAwait( false );
        } catch ( Exception ex ) {
            exceptions.Add( ex );

            if ( retries < maxRetries )
                await Task.Delay( 500, cancelToken ).ConfigureAwait( false ); //ease up a bit
            else
                throw new AggregateException( "Retry limit reached", exceptions );
        }

    exceptions.Add( new OperationCanceledException( cancelToken ) );
    throw new AggregateException( "Retry loop was canceled", exceptions );
}
0

I had the need to pass some parameter to my method to retry, and have a result value; so i need an expression.. I build up this class that does the work (it is inspired to the the LBushkin's one) you can use it like this:

static void Main(string[] args)
{
    // one shot
    var res = Retry<string>.Do(() => retryThis("try"), 4, TimeSpan.FromSeconds(2), fix);

    // delayed execute
    var retry = new Retry<string>(() => retryThis("try"), 4, TimeSpan.FromSeconds(2), fix);
    var res2 = retry.Execute();
}

static void fix()
{
    Console.WriteLine("oh, no! Fix and retry!!!");
}

static string retryThis(string tryThis)
{
    Console.WriteLine("Let's try!!!");
    throw new Exception(tryThis);
}

public class Retry<TResult>
{
    Expression<Func<TResult>> _Method;
    int _NumRetries;
    TimeSpan _RetryTimeout;
    Action _OnFailureAction;

    public Retry(Expression<Func<TResult>> method, int numRetries, TimeSpan retryTimeout, Action onFailureAction)
    {
        _Method = method;
        _NumRetries = numRetries;
        _OnFailureAction = onFailureAction;
        _RetryTimeout = retryTimeout;
    }

    public TResult Execute()
    {
        TResult result = default(TResult);
        while (_NumRetries > 0)
        {
            try
            {
                result = _Method.Compile()();
                break;
            }
            catch
            {
                _OnFailureAction();
                _NumRetries--;
                if (_NumRetries <= 0) throw; // improved to avoid silent failure
                Thread.Sleep(_RetryTimeout);
            }
        }
        return result;
    }

    public static TResult Do(Expression<Func<TResult>> method, int numRetries, TimeSpan retryTimeout, Action onFailureAction)
    {
        var retry = new Retry<TResult>(method, numRetries, retryTimeout, onFailureAction);
        return retry.Execute();
    }
}

ps. the LBushkin's solution does one more retry =D

0

I would add the following code to the accepted answer

public static class Retry<TException> where TException : Exception //ability to pass the exception type
    {
        //same code as the accepted answer ....

        public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
        {
            var exceptions = new List<Exception>();

            for (int retry = 0; retry < retryCount; retry++)
            {
                try
                {
                    return action();
                }
                catch (TException ex) //Usage of the exception type
                {
                    exceptions.Add(ex);
                    Thread.Sleep(retryInterval);
                }
            }

            throw new AggregateException(String.Format("Failed to excecute after {0} attempt(s)", retryCount), exceptions);
        }
    }

Basically the above code is making the Retry class generic so you can pass the type of the exception you want to catch for retry.

Now use it almost in the same way but specifying the exception type

Retry<EndpointNotFoundException>.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
3
  • The for loop will always execute a couple of times (based on your retryCount) even if the code in TRY CATCH loop was executed without exceptions. I would suggest to set retryCount equal to the retry var in the try loop, so the for loop wil stop going over it.
    – scre_www
    Commented Sep 8, 2017 at 8:32
  • @scre_www I believe you're mistaken. If action doesn't throw then Do returns thus breaking away from the for loop.
    – HappyNomad
    Commented Feb 1, 2020 at 15:46
  • In any case, there's a problem with this implementation. After the final retry, right before giving up, Thread.Sleep is called for no reason.
    – HappyNomad
    Commented Feb 1, 2020 at 15:48
0

I know this answer is very old but I just wanted to comment on this because I have run into issues using these while, do, whatever statement with counters.

Over the years I have settled on a better approach I think. That is to use some sort of event aggregation like a reactive extensions "Subject" or the like. When a try fails, you simply publish an event saying the try failed, and have the aggregator function re-schedule the event. This allows you much more control over the retry without polluting the call itself with a bunch of retry loops and what not. Nor are you tying up a single thread with a bunch of thread sleeps.

0

Do it simple in C#, Java or other languages:

  internal class ShouldRetryHandler {
    private static int RETRIES_MAX_NUMBER = 3;
    private static int numberTryes;

    public static bool shouldRetry() {
        var statusRetry = false;

        if (numberTryes< RETRIES_MAX_NUMBER) {
            numberTryes++;
            statusRetry = true;
            //log msg -> 'retry number' + numberTryes

        }

        else {
            statusRetry = false;
            //log msg -> 'reached retry number limit' 
        }

        return statusRetry;
    }
}

and use it in your code very simple:

 void simpleMethod(){
    //some code

    if(ShouldRetryHandler.shouldRetry()){
    //do some repetitive work
     }

    //some code    
    }

or you can use it in recursive methods:

void recursiveMethod(){
    //some code

    if(ShouldRetryHandler.shouldRetry()){
    recursiveMethod();
     }

    //some code    
    }
0

It is also possible to use a recursive retry, by simply returning itself with an attempt counter when you need to retry. Then you need two extra parameters, one for the attempt counter, and one for the number of max attempts. Remember to increase the attempt counter upon retry. If you use an interface, you can choose to add the parameters to the interface, or add a wrapper method that calls the method with those parameters. Here is an example of the latter.

public interface ISomeService
{
  Task TryThreeTimes();
}

public class SomeService : ISomeService
{
  public async Task TryTreeTimes() {
    return await TryTreeTimes(attempt = 0, maxAttempt = 3);
  }

  private void TryTreeTimes(int attempt = 0, int maxAttempt = 3)
  {
    try
    {
      // execute code
    }
    catch (Exception exception)
    {
      // handle exception

      var needToRetry = /*some condition*/ true;
      if (needToRetry && attempt < maxAttempt)
      {
        await Task.Delay(1000);
        return TryTreeTimes(attempt + 1, maxAttempt);
      }
    }
  }
}

Make sure to handle any disposable variables properly to avoid memory leak, for instance with a finally block at the end. Remember that this will recursively add data to the stack, so be advised to balance memory usage with max possible attempts.

0

There are many good answers already, but most of them should be improved by not rethrowing at the end, instead use catch (...) when ... (since C# 6)

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed.

/// <summary>
/// Retries an async action when a specific exception occurs, on last try the exception is not catched
/// </summary>
public static async Task RetryAsync<T>(Func<Task> action, int tries = 3, int sleep = 0, ILogger? logger = null) where T : Exception
{
    while (true)
    {
        try
        {
            await action();
            return;
        }
        catch (T ex) when (--tries > 0)
        {
            logger?.LogError(ex, "{Message}\nRetrying ({tries} remaining)...", ex.Message, tries);
            await Task.Delay(sleep);
        }
    }
}

/// <summary>
/// Retries an action when a specific exception occurs, on last try the exception is not catched
/// </summary>
public static void Retry<T>(Action action, int tries = 3, int sleep = 0, ILogger? logger = null) where T : Exception
{
    while (true)
    {
        try
        {
            action();
            return;
        }
        catch (T ex) when (--tries > 0)
        {
            logger?.LogError(ex, "{Message}\nRetrying ({tries} remaining)...", ex.Message, tries);
            Thread.Sleep(sleep);
        }
    }
}

//TODO: we need additional versions to return results

Fiddle

-1

Or how about doing it a bit neater....

int retries = 3;
while (retries > 0)
{
  if (DoSomething())
  {
    retries = 0;
  }
  else
  {
    retries--;
  }
}

I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries (such as building a library other people can use). Why not just have the DoSomething() command return true if it was successful and false otherwise?

EDIT: And this can be encapsulated inside a function like others have suggested as well. Only problem is if you are not writing the DoSomething() function yourself

1
  • 8
    "I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries" - I completely disagree. How do you know the caller checked your false (or worse, null) return? WHY did the code fail? False tells you nothing else. What if the caller has to pass the failure up the stack? Read msdn.microsoft.com/en-us/library/ms229014.aspx - these are for libraries, but they make just as much sense for internal code. And on a team, other people are likely to call your code.
    – TrueWill
    Commented Oct 14, 2009 at 1:28
-1
int retries = 3;
while (true)
{
    try
    {
        //Do Somthing
        break;
    }
    catch (Exception ex)
    {
        if (--retries == 0)
            return Request.BadRequest(ApiUtil.GenerateRequestResponse(false, "3 Times tried it failed do to : " + ex.Message, new JObject()));
        else
            System.Threading.Thread.Sleep(100);
    }
1
  • What do you do with Request.BadRequest?
    – Danh
    Commented Dec 20, 2016 at 8:59
-1

I've implemented an async version of the accepted answer like so - and it seems to work nicely - any comments?


        public static async Task DoAsync(
            Action action,
            TimeSpan retryInterval,
            int maxAttemptCount = 3)
        {
            DoAsync<object>(() =>
            {
                action();
                return null;
            }, retryInterval, maxAttemptCount);
        }

        public static async Task<T> DoAsync<T>(
            Func<Task<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 await action();
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }
            throw new AggregateException(exceptions);
        }

And, call it simply like this:

var result = await Retry.DoAsync(() => MyAsyncMethod(), TimeSpan.FromSeconds(5), 4);
1
  • Thread.Sleep? Blocking a thread negates the benefits of asynchrony. Also I am pretty sure that the Task DoAsync() version should accept an argument of type Func<Task>. Commented May 13, 2020 at 15:50
-2
public delegate void ThingToTryDeletage();

public static void TryNTimes(ThingToTryDelegate, int N, int sleepTime)
{
   while(true)
   {
      try
      {
        ThingToTryDelegate();
      } catch {

            if( --N == 0) throw;
          else Thread.Sleep(time);          
      }
}
1
  • 1
    Because the throw; is the only way the infinite loop is terminated, this method is actually implementing "try until it fails N times" and not the desired "try up to N times until it succeeds". You need a break; or return; after the call to ThingToTryDelegate(); otherwise it'll be called continuously if it never fails. Also, this won't compile because the first parameter of TryNTimes has no name. -1. Commented Sep 7, 2017 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.