Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created October 12, 2010 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jpoehls/622195 to your computer and use it in GitHub Desktop.
Save jpoehls/622195 to your computer and use it in GitHub Desktop.
Tries to perform an action several times before giving up
using System;
using System.Threading;
using log4net;
namespace Samples
{
public class EngineThatCould
{
private static readonly ILog Log = LogManager.GetLogger(typeof(EngineThatCould));
private const int SecondsBetweenAttempts = 1;
private const int MaxAttempts = 5;
public Func<Exception, bool> ShouldExpect { get; set; }
public void Chug(Action action, string actionDesc)
{
if (action == null)
throw new ArgumentNullException("action");
if (actionDesc == null)
throw new ArgumentNullException("actionDesc");
if (ShouldExpect == null)
throw new InvalidOperationException("ShouldExpect can't be null!");
int attemptCount = 1;
while (attemptCount <= MaxAttempts)
{
try
{
action();
Log.InfoFormat("Successfully \"{0}\"", actionDesc);
}
catch (Exception ex)
{
if (ShouldExpect(ex))
{
if (attemptCount == MaxAttempts)
{
Log.Error("Failed to \"" + actionDesc + "\" after attempt " + attemptCount, ex);
}
else
{
Thread.Sleep(SecondsBetweenAttempts*1000);
}
}
}
attemptCount++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment