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?
Do it simple in C#, Java or other languages:
and use it in your code very simple:
or you can use it in recursive methods: