Skip to content

Instantly share code, notes, and snippets.

@msajid
Last active August 29, 2015 14:07
Show Gist options
  • Save msajid/aef9fd17af51a66ed684 to your computer and use it in GitHub Desktop.
Save msajid/aef9fd17af51a66ed684 to your computer and use it in GitHub Desktop.
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