LoginSignup
1
2

More than 3 years have passed since last update.

C#でPollyを使ったリトライ処理

Posted at

nugetでPollyをインストールしたら後は下記のように実装するだけです。
今回はAzureSQLDatabaseを使用するため、シンプルに指定したエラーの際にリトライするよう実装しました。

RetryHelper.cs

using Polly;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace Common
{

    public static class RetryHelper
    {
        public static void OpenWithRetry(this SqlConnection connection)
        {

            PolicyResult policyResult = Policy.Handle<SqlException>(ex => TransientErrorNumbers.Contains(ex.Number))
                .Retry(3)
                .ExecuteAndCapture(connection.Open);

            if (policyResult.Outcome == OutcomeType.Failure)
            {
                // 実行に失敗した
                if (policyResult.FinalException is SqlException)
                {
                    SqlConnection.ClearPool(connection);

                    throw policyResult.FinalException;
                    // FinalException に例外が格納されている
                }
            }
        }

        private static readonly HashSet<int> TransientErrorNumbers = new HashSet<int>
        {
            50000,
            40197,
            40501,
            10053,
            10054,
            10060,
            40613,
            40143,
            233,
            121,
            64,
            53,
            20,
             -2
        };

    }

}

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2