Created
October 12, 2010 13:54
-
-
Save jpoehls/622195 to your computer and use it in GitHub Desktop.
Tries to perform an action several times before giving up
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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