53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace AyaNova.Util
|
|
{
|
|
|
|
/// <summary>
|
|
/// what it says
|
|
/// </summary>
|
|
public static class RetryHelper
|
|
{
|
|
//private static ILog logger = LogManager.GetLogger(); //use a logger or trace of your choice
|
|
// private readonly ILogger log;
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="times"></param>
|
|
/// <param name="delay"></param>
|
|
/// <param name="log"></param>
|
|
/// <param name="logPrepend"></param>
|
|
/// <param name="operation"></param>
|
|
public static void RetryOnException(int times, TimeSpan delay, ILogger log, string logPrepend, Action operation)
|
|
{
|
|
var attempts = 0;
|
|
do
|
|
{
|
|
try
|
|
{
|
|
attempts++;
|
|
operation();
|
|
break; // Sucess! Lets exit the loop!
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (attempts == times)
|
|
throw;
|
|
|
|
log.LogError(ex, $"{logPrepend} Exception caught on attempt {attempts} of {times} - will retry after delay {delay}");
|
|
|
|
Task.Delay(delay).Wait();
|
|
}
|
|
} while (true);
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
} |