Reputation: 10792
Inspired by Cleanest way to write retry logic? I made this
public static T Retry<T>(int numRetries, int timeout, Delegate method, params object[] args)
{
if (method == null)
throw new ArgumentNullException("method");
var retval = default(T);
do
{
try
{
retval = (T) method.DynamicInvoke(args);
return retval;
}
catch (TimeoutException)
{
if (numRetries <= 0)
throw; // avoid silent failure
Thread.Sleep(timeout);
}
} while (numRetries-- > 0);
return retval;
}
However I've run into the method group problem.
Test setup
private int Add(int x, int y)
{
return x + y;
}
public static void Main(string[] args)
{
var r = Retry<int>(5, 10, Add, 1, 1);
}
Is there no better way to fix this other then Retry<int>(5, 10, new Func<int, int, int>(Add), 1, 1);
Upvotes: 2
Views: 80
Reputation: 35363
You can change Retry
to
public static T Retry<T>(int numRetries, int timeout, Func<T> method)
{
if (method == null)
throw new ArgumentNullException("method");
var retval = default(T);
do
{
try
{
retval = method();
return retval;
}
catch (TimeoutException)
{
if (numRetries <= 0)
throw; // avoid silent failure
Thread.Sleep(timeout);
}
} while (numRetries-- > 0);
return retval;
}
and call as
var result = Retry(5, 10, ()=>Add(1,1));
Upvotes: 4