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:
You can now use this utility method to perform retry logic:
or:
or:
Or you could even make an
async
overload.Keep it simple with C# 6.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:
ps. the LBushkin's solution does one more retry =D
Implemented LBushkin's answer in the latest fashion:
and to use it:
whereas the function
[TaskFunction]
can either beTask<T>
or justTask
.The Transient Fault Handling Application Block provides an extensible collection of retry strategies including:
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').
Allowing for functions and retry messages