I created this class which supposed to take a method and try to execute it. If it fails lets say 10 times, it will throw the original exception thrown by the delegate.
Do you have any ideas for improvement about that code?
I am particularly interested, in where to put this code. Right now it is within a FileHandler
assembly because the code was used for serialization.
But since it can be used generally I want to move it to a different assembly. Unfortunately I did not come up with a better name (other than "Utility" or "Helper"). Unfortunately I did not come with a really meaningful name...maybe something related to "invoke" or so?
public static class FileHandler
{
private const int MAX_TRIES = 10;
private const int WAIT_FOR_RETRY_DELAY = 250;
public static T ExecuteFuncWithRetry<T>(Func<T> func, string errorMessage)
{
var retryFunc = new FuncWithRetry<T>(errorMessage, func);
var ret = retryFunc.PerformAction();
return ret;
}
private class FuncWithRetry<T>
{
private readonly string _errorMessage;
private readonly Func<T> _func;
public FuncWithRetry(string errorMessage, Func<T> func)
{
_errorMessage = errorMessage;
_func = func;
}
public T PerformAction()
{
var tries = 1;
Exception exception = null;
do
{
try
{
var retval = _func();
return retval;
}
catch (Exception e)
{
exception = e;
Thread.Sleep(WAIT_FOR_RETRY_DELAY);
}
finally
{
tries++;
}
} while (tries <= MAX_TRIES);
throw new Exception(_errorMessage, exception);
}
}
}
MAX_TRIES
are never declared). I assume you're just missing a couple ofconst
declarations, but it's still helpful to have them in there for completeness \$\endgroup\$throw Exception
. I'd consider wrapping all exceptions (each attempt might have returned a different one) in anAggregateException
. \$\endgroup\$