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?
I'm a fan of recursion and extension methods, so here are my two cents:
I needed a method that supports cancellation, while I was at it, I added support for returning intermediate failures.
You can use the
Retry
function like this, retry 3 times with a 10 second delay but without cancellation.Or, retry eternally every five seconds, unless cancelled.
As you can guess, In my source code I've overloaded the
Retry
function to support the differing delgate types I desire to use.My
async
implementation of the retry method:Key points: I used
.ConfigureAwait(false);
andFunc<dynamic>
insteadFunc<T>
I've written a small class based on answers posted here. Hopefully it will help someone: https://github.com/natenho/resiliency
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