Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created November 28, 2012 01:39
Show Gist options
  • Save ajjames/4158497 to your computer and use it in GitHub Desktop.
Save ajjames/4158497 to your computer and use it in GitHub Desktop.
Simple retry class
using System;
using System.Threading;
using NUnit.Framework;
namespace Tests
{
class RetryManager
{
public void AttemptToRetryUntilTrue(Func<bool> condition, int timeoutMilliseconds = 5000, int delayMiliseconds = 100)
{
AttemptToRetryUntilTrue(condition, null, timeoutMilliseconds, delayMiliseconds);
}
public void AttemptToRetryUntilTrue(Func<bool> condition, Exception error = null, int timeoutMilliseconds = 5000, int delayMiliseconds = 100)
{
var startTime = DateTime.Now;
var timeToQuit = startTime.AddMilliseconds(timeoutMilliseconds);
var attempts = 0;
while (DateTime.Now < timeToQuit)
{
attempts++;
if (attempts > 1)
Console.WriteLine("Retrying...");
try
{
if (condition())
return;
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
Thread.Sleep(delayMiliseconds);
}
if (null == error)
error = new Exception("Error: Timeout exceeded!");
throw error;
}
}
[TestFixture]
public class RetryTests
{
[Test]
public void VerifyRetries3Times()
{
var retryMan = new RetryManager();
var count = 0;
Func<bool> counter = () =>
{
count++;
if (count < 3)
return false;
return true;
};
retryMan.AttemptToRetryUntilTrue(counter, 5000, 0);
Assert.AreEqual(3, count);
}
[Test, ExpectedException("System.StackOverflowException")]
public void VerifyRetriesFail()
{
var retryMan = new RetryManager();
Func<bool> counter = () =>
{
throw new Exception();
};
retryMan.AttemptToRetryUntilTrue(counter, new StackOverflowException(), 100, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment