So far I implemented this:
public class Retrier
{
/// <summary>
/// Execute a method with no parameters multiple times with an interval
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="function"></param>
/// <param name="tryTimes"></param>
/// <param name="interval"></param>
/// <returns></returns>
public static TResult Execute<TResult>(Func<TResult> function, int tryTimes, int interval)
{
for (int i = 0; i < tryTimes - 1; i++)
{
try
{
return function();
}
catch (Exception)
{
Thread.Sleep(interval);
}
}
return function();
}
/// <summary>
/// Execute a method with 1 parameter multiple times with an interval
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="function"></param>
/// <param name="arg1"></param>
/// <param name="tryTimes"></param>
/// <param name="interval"></param>
/// <returns></returns>
public static TResult Execute<T, TResult>(Func<T, TResult> function, T arg1, int tryTimes, int interval)
{
for (int i = 0; i < tryTimes - 1; i++)
{
try
{
return function(arg1);
}
catch (Exception)
{
Thread.Sleep(interval);
}
}
return function(arg1);
}
/// <summary>
/// Execute a method with 2 parameters multiple times with an interval
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="function"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="tryTimes"></param>
/// <param name="interval"></param>
/// <returns></returns>
public static TResult Execute<T1, T2, TResult>(Func<T1, T2, TResult> function, T1 arg1, T2 arg2, int tryTimes, int interval)
{
for (int i = 0; i < tryTimes - 1; i++)
{
try
{
return function(arg1, arg2);
}
catch (Exception)
{
Thread.Sleep(interval);
}
}
return function(arg1, arg2);
}
}
The problem is that it becomes difficult to maintain.
When I have a method with more variables, I need to implement another Execute
method.
In case I need to change anything I have to change it in all methods.
So I wonder if there is a clean way to make it one method that will handle any number of parameters?