LANCommander/LANCommander.SDK/Helpers/RetryHelper.cs

37 lines
920 B
C#
Raw Normal View History

using Microsoft.Extensions.Logging;
2023-08-21 23:44:20 +00:00
using System;
using System.Threading.Tasks;
namespace LANCommander.SDK.Helpers
{
internal static class RetryHelper
{
internal static readonly ILogger Logger;
2023-08-21 23:44:20 +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
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
if (attempts >= maxAttempts)
return @default;
Task.Delay(delay).Wait();
}
} while (true);
}
}
}