Add retry helper method

This commit is contained in:
niksedk 2021-06-24 19:00:45 +02:00
parent cec6a489d3
commit bd69e6413a

40
src/libse/Common/Retry.cs Normal file
View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace Nikse.SubtitleEdit.Core.Common
{
public class Retry
{
public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, maxAttemptCount);
}
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount)
{
var lastException = new Exception();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
Thread.Sleep(retryInterval);
}
return action();
}
catch (Exception ex)
{
lastException = ex;
}
}
throw lastException;
}
}
}