在 C# 中优雅地实现重试逻辑
在软件开发中,某些操作可能需要多次尝试才能成功完成。传统方法通常使用带有显式重试次数的 while
循环,例如以下代码:
<code class="language-csharp">int retries = 3; while (true) { try { DoSomething(); break; // 成功! } catch { if (--retries == 0) throw; else Thread.Sleep(1000); } }</code>
这种方法虽然确保了操作会重试预定义的次数,但在不同情况下编写起来可能会比较繁琐。更通用的方法可以提供更简洁且可重用的解决方案。
引入 Retry
类
目标是创建一个可重用的 Retry
类,它接受一个委托作为参数,并在重试块中执行操作。以下代码提供了一种可能的实现:
<code class="language-csharp">public static class Retry { public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { Do(() => { action(); return null; }, retryInterval, maxAttemptCount); } public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { return action(); } catch (Exception ex) { exceptions.Add(ex); if (attempted < maxAttemptCount -1) { Thread.Sleep(retryInterval); } } } throw new AggregateException(exceptions); } }</code>
使用 Retry
类
此方法可用于各种方式来实现重试逻辑:
<code class="language-csharp">Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1)); Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1)); int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);</code>
如所示,该方法提供了一种灵活的方式来处理重试,能够指定尝试次数、重试间隔和要执行的操作。
以上是如何在C#中优雅地实现重试逻辑?的详细内容。更多信息请关注PHP中文网其他相关文章!