LANCommander/LANCommander.SDK/Helpers/RetryHelper.cs

114 lines
3 KiB
C#
Raw Permalink Normal View History

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