From bd69e6413ade75e3c7f4c2d72a6fc6b327e77cd9 Mon Sep 17 00:00:00 2001 From: niksedk Date: Thu, 24 Jun 2021 19:00:45 +0200 Subject: [PATCH] Add retry helper method --- src/libse/Common/Retry.cs | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/libse/Common/Retry.cs diff --git a/src/libse/Common/Retry.cs b/src/libse/Common/Retry.cs new file mode 100644 index 000000000..fb605052f --- /dev/null +++ b/src/libse/Common/Retry.cs @@ -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(() => + { + action(); + return null; + }, retryInterval, maxAttemptCount); + } + + public static T Do(Func 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; + } + } +}