Skip to content

Instantly share code, notes, and snippets.

@msajid
Last active Aug 29, 2015
Embed
What would you like to do?
a custom retry helper class with Action and Func of T.
using System;
using System.Threading;
namespace RetrySolution
{
public static class RetryManager
{
private const int RetryCount = 3;
private const int RetryTimeoutInMillis = 100;
public static void TryExecute(Action action)
{
if (action == null) return;
var numberOfRetries = RetryCount;
do
{
try
{
action();
return;
}
catch (TimeoutException ex)
{
if (numberOfRetries == 0)
{
throw;
}
Thread.Sleep(RetryTimeoutInMillis);
}
catch (Exception ex)
{
if (numberOfRetries == 0)
{
throw;
}
Thread.Sleep(RetryTimeoutInMillis);
}
}
while (numberOfRetries-- > 0);
}
public static T TryExecute<T>(Func<T> func)
{
if (func == null) return default(T);
var numberOfRetries = RetryCount;
do
{
try
{
return func();
}
catch (TimeoutException ex)
{
if (numberOfRetries == 0)
{
throw;
}
Thread.Sleep(RetryTimeoutInMillis);
}
catch (Exception ex)
{
if (numberOfRetries == 0)
{
throw;
}
Thread.Sleep(RetryTimeoutInMillis);
}
}
while (numberOfRetries-- > 0);
return default(T);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment