DocSpace-buildtools/common/ASC.Data.Backup.Core/ActionInvoker.cs

54 lines
1.4 KiB
C#
Raw Normal View History

namespace ASC.Data.Backup;
public static class ActionInvoker
2020-05-20 15:14:44 +00:00
{
public static void Try(
Action action,
int maxAttempts,
Action<Exception> onFailure = null,
Action<Exception> onAttemptFailure = null,
int sleepMs = 1000,
bool isSleepExponential = true)
{
Try(state => action(), null, maxAttempts, onFailure, onAttemptFailure, sleepMs, isSleepExponential);
}
public static void Try(
Action<object> action,
object state,
int maxAttempts,
Action<Exception> onFailure = null,
Action<Exception> onAttemptFailure = null,
int sleepMs = 1000,
bool isSleepExponential = true)
2022-03-09 17:15:51 +00:00
{
ArgumentNullException.ThrowIfNull(action);
2020-05-20 15:14:44 +00:00
var countAttempts = 0;
while (countAttempts++ < maxAttempts)
2020-05-20 15:14:44 +00:00
{
try
2022-02-09 16:46:09 +00:00
{
action(state);
return;
2022-02-09 16:46:09 +00:00
}
catch (Exception error)
2020-05-20 15:14:44 +00:00
{
if (countAttempts < maxAttempts)
2020-05-20 15:14:44 +00:00
{
onAttemptFailure?.Invoke(error);
2020-05-20 15:14:44 +00:00
if (sleepMs > 0)
2020-05-20 15:14:44 +00:00
{
Thread.Sleep(isSleepExponential ? sleepMs * countAttempts : sleepMs);
2020-05-20 15:14:44 +00:00
}
}
else
{
onFailure?.Invoke(error);
}
2020-05-20 15:14:44 +00:00
}
}
}
}