Skip to content

Instantly share code, notes, and snippets.

@randyburden
Created April 16, 2021 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randyburden/32fa86f2f4a85fbc272e7d0c951e30e1 to your computer and use it in GitHub Desktop.
Save randyburden/32fa86f2f4a85fbc272e7d0c951e30e1 to your computer and use it in GitHub Desktop.
Retry Helpers
using System;
using System.Threading;
namespace Helpers
{
/// <summary>
/// Retry helpers.
/// </summary>
public static class RetryHelper
{
/// <summary>
/// Retries up to the given <see cref="maxRetryCount"/> before throwing an exception.
/// </summary>
/// <param name="action">Action to perform.</param>
/// <param name="maxRetryCount">Max retry count before throwing an exception. Default is 3.</param>
/// <returns>Returns the number of retry attempts. Returns 0 if no retries were attempted.</returns>
public static int Retry(Action action, int maxRetryCount = 3)
{
var retryCount = 0;
try
{
action();
}
catch (Exception)
{
retryCount++;
if (retryCount >= maxRetryCount)
{
throw;
}
}
return retryCount;
}
/// <summary>
/// Retries up to the given <see cref="retryDuration"/> before throwing an exception.
/// </summary>
/// <param name="action">Action to perform.</param>
/// <param name="retryDuration">Retry duration before throwing an exception.</param>
/// <returns>Returns the number of retry attempts. Returns 0 if no retries were attempted.</returns>
public static int Retry(Action action, TimeSpan retryDuration)
{
var retryCount = 0;
var cts = new CancellationTokenSource(retryDuration);
try
{
action();
}
catch (Exception)
{
retryCount++;
if (cts.IsCancellationRequested)
{
throw;
}
}
return retryCount;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment