I have a method which should accept a Function/Action and do something with that method (in my case I've added retry logic).
I'm wondering how I can remove the duplicated code (for loop, etc) from the last 2 methods. Is there any clever way to do this in C#?
public static class Retry {
public static void Do(
Type retryOnExceptionType,
Action action,
TimeSpan retryInterval =
default (TimeSpan),
int retryCount = 3) {
if (retryInterval ==
default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);
Do < object > (
retryOnExceptionType, () = > {
action();
return null;
}, retryInterval, retryCount);
}
public static T1 Do < T1, T2, T3 > (
Type retryOnExceptionType,
Func < T2, T3, T1 > action,
T2 param1,
T3 param2,
TimeSpan retryInterval =
default (TimeSpan),
int retryCount = 3) {
if (retryInterval ==
default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);
var exceptions = new List < Exception > ();
for (int retry = 0; retry < retryCount; retry++) {
try {
return action(param1, param2);
} catch (Exception ex) {
if (!retryOnExceptionType.IsInstanceOfType(ex)) throw;
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(exceptions);
}
public static T Do < T > (
Type retryOnExceptionType,
Func < T > action,
TimeSpan retryInterval =
default (TimeSpan),
int retryCount = 3) {
if (retryInterval ==
default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);
var exceptions = new List < Exception > ();
for (int retry = 0; retry < retryCount; retry++) {
try {
return action();
} catch (Exception ex) {
if (!retryOnExceptionType.IsInstanceOfType(ex)) throw;
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(exceptions);
}
}