Cleanest way to write retry logic?

what is retry logic
c# retry task with delay
c# async retry pattern
retry logic python
httpclient retry c#
api retry logic
c# webclient retry
polly retry policy example c#

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?

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.

Implementing a simple retry pattern in c#, If you make an outbound call you probably need an easy way to retry a Retry logic should not obscure the actual application logic making  Polly : Cleanest way to write "Retry logic". Set up a policy handle with the number of attempts you would like to retry. Use the policy’s ExecuteAndCapture method to call the logic you intend to retry If the logic still fails after the specified number of attempts then the "Exception

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, retryAttempt => TimeSpan.FromSeconds(3))
    .Execute(() => DoSomething());

Cleanest way to write Retry logic ?, Hi I have to write Retry logic on my project ie: if the first time the user click something or Send a request - it goes for Business logic to execute  Hi I have to write Retry logic on my project ie: if the first time the user click something or Send a request - it goes for Business logic to execute some method then get update on DB , So if there

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 an notification about a failure three times on packet failure.

Now suppose the notification layer reactivates the notification three times on an 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.

Cleanest way to write a retry logic. Reference from: http , Cleanest way to write a retry logic. Reference from: http://stackoverflow.com/​questions/1563191/c-sharp-cleanest-way-to-write-retry-logic#answer-1563234  Cleanest way to write retry logic? has some interesting ideas, but I would like to avoid complicating the code across dozens of calls. I think I need to implement a SOAPExtension to check for retrySpecific exceptions and then perform an internal retry.

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

A simple retry mechanism for C# · GitHub, //http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-​logic. public static class Retry. {. public static void Do(Action action, TimeSpan  Is there a better way to write this code without using goto? It seems awkward, but I can't think of a better way. It seems awkward, but I can't think of a better way. I need to be able to perform one retry attempt, but I don't want to duplicate any code.

c Cleanest way to write retry logic?, Making it an Action extension method static class ActionExtensions { public static void InvokeAndRetryOnException<T> (this Action action, int retries, TimeSpan  I'm trying to implement some retry logic base on this post (but with tasks) Cleanest way to write retry logic? The idea for the retry logic is to then to implement a second task that triggers the cancelation after a give amount of time

Polly : Cleanest way to write “Retry logic”., Polly : Cleanest way to write “Retry logic”. With the advent of MicroService architecture, there came a need to effectively handle exceptions  Polly : Cleanest way to write “Retry logic”. With the advent of MicroService architecture, there came a need to effectively handle exceptions calling WebAPI . This can also be said to be true about handling database exceptions in a timely and clean manner.

C# - Generic Retry Mechanism, Demo for generic retry mechanism. There are three methods needed to execute from the main method, if it fails, the main method will retry the failed methods. type</typeparam> /// <param name="action">Method needs to be executed</param> NET developers to express retry logic using a fluent-api. is there a way to get a function to repeat itself if a condition isnt met [duplicate] Ask Question Asked 6 years, Cleanest way to write retry logic?

Python code to retry function, It's weird to me that this function does have any concept of retrying after That also uses a Python 3 only feature; I've left a comment for how to do it in Python 2. asyncio.sleep(delay) if last_exception is not None: raise type(last_exception)  Retry logic should not obscure the actual application logic making code harder to understand later. Retry logic is probably a cross cutting concern and should be centralised. Avoid duplicating that retry looping code. You may want to be able to configure the retry behaviour without recompilation.

Comments
  • A simple cycle is not enough? Why just not to iterate over and execute logic for several times?
  • 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.
  • 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.
  • @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.
  • +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.
  • 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.
  • 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.
  • @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.
  • 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) });
  • 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?
  • +1. Raymond shares a real life example here, blogs.msdn.com/oldnewthing/archive/2005/11/07/489807.aspx
  • -1 This advice is useless for transient network failures encountered by automated batch processing systems.