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?
Use Polly
https://github.com/App-vNext/Polly-Samples
Here is a retry-generic I use with Polly
Use it like this
I would add the following code to the accepted answer
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
For those who want to have both the option to retry on any exception or explicitly set the exception type, use this:
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?
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.
I'd implement this:
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 aFunc<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:
or
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 aFunc<bool>
as well.Exponential backoff is a good retry strategy than simply trying x number of times. You can use a library like Polly to implement it.