diff --git a/Shared/Utils/ResilientUtils.cs b/Shared/Utils/ResilientUtils.cs index 33ce379..e85bc3f 100644 --- a/Shared/Utils/ResilientUtils.cs +++ b/Shared/Utils/ResilientUtils.cs @@ -11,6 +11,11 @@ public static class ResilientUtils { /// public static void RetryOn(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException : Exception => RetryOn(() => { action(); return null; }, maxAttempts, delayMs, caller); + /// + /// 在抛出特定异常时,延迟并自动重试。 + /// + public static void RetryOn(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException1 : Exception where TException2 : Exception + => RetryOn(() => { action(); return null; }, maxAttempts, delayMs, caller); /// /// 在抛出任意异常时,延迟并自动重试。 @@ -37,5 +42,25 @@ public static class ResilientUtils { } } } + /// + /// 在抛出特定异常时,延迟并自动重试。 + /// + public static TOut RetryOn(Func func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException1 : Exception where TException2 : Exception { + int attempt = 0; + while (true) { + try { + return func(); // 成功则退出 + } catch (Exception ex) when (ex is TException1 or TException2) { + attempt++; + if (attempt < maxAttempts) { + Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试"); + Thread.Sleep(delayMs); + } else { // 超过最大尝试次数 + Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数"); + throw; + } + } + } + } }