在 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中文網其他相關文章!