2023-11-10 01:40:38 +00:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
2023-08-21 23:44:20 +00:00
|
|
|
|
using System;
|
2023-03-20 23:37:12 +00:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2023-11-10 01:40:38 +00:00
|
|
|
|
namespace LANCommander.SDK.Helpers
|
2023-03-20 23:37:12 +00:00
|
|
|
|
{
|
|
|
|
|
internal static class RetryHelper
|
|
|
|
|
{
|
2023-11-10 01:40:38 +00:00
|
|
|
|
internal static readonly ILogger Logger;
|
2023-08-21 23:44:20 +00:00
|
|
|
|
|
2023-03-20 23:37:12 +00:00
|
|
|
|
internal static T RetryOnException<T>(int maxAttempts, TimeSpan delay, T @default, Func<T> action)
|
|
|
|
|
{
|
|
|
|
|
int attempts = 0;
|
|
|
|
|
|
|
|
|
|
do
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2023-11-11 02:53:28 +00:00
|
|
|
|
Logger?.LogTrace($"Attempt #{attempts + 1}/{maxAttempts}...");
|
2023-08-21 23:44:20 +00:00
|
|
|
|
|
2023-03-20 23:37:12 +00:00
|
|
|
|
attempts++;
|
|
|
|
|
return action();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2023-11-11 02:53:28 +00:00
|
|
|
|
Logger?.LogError(ex, $"Attempt failed!");
|
2023-08-21 23:44:20 +00:00
|
|
|
|
|
2023-03-20 23:37:12 +00:00
|
|
|
|
if (attempts >= maxAttempts)
|
|
|
|
|
return @default;
|
|
|
|
|
|
|
|
|
|
Task.Delay(delay).Wait();
|
|
|
|
|
}
|
|
|
|
|
} while (true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|