首頁 > 後端開發 > C++ > 如何在C#中優雅地實現重試邏輯?

如何在C#中優雅地實現重試邏輯?

DDD
發布: 2025-01-29 08:32:11
原創
434 人瀏覽過

How to Elegantly Implement Retry Logic in C#?

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板