Files
sockeye/server/util/RetryHelper.cs
2022-12-16 06:01:23 +00:00

52 lines
1.2 KiB
C#

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Sockeye.Util
{
/// <summary>
/// what it says
/// </summary>
public static class RetryHelper
{
/// <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);
}
}
}