SoFunction
Updated on 2025-03-08

Implementation method of C# exception execution retry

A mode introduction

Retry mode is used in exception handling. When an exception occurs, it can re-call the business program. In reality, Polly can be used to provide stable and simple usage. The implementation of it yourself is mainly an understanding of the mode.

Two mode implementation

public class RetryPattern
    {
        /**
          * Retry mode can be replaced by Polly
          * Implement a model yourself
          */

        #region constructor
        public RetryPattern()
        {
        }

        #endregion constructor
        #region variable
        private uint MaxTryCount; // Maximum number of retry        private uint CurrentTryCount; // The current number of retry        private bool RunResult = true; // Execution results
        #endregion variable
        #region method
        #region Set the maximum number of retry
        public void SetMaxCount(uint tryCount)
        {
            // Verification            if (tryCount == 0) throw new ArgumentException("The number of retry cannot be 0");

            MaxTryCount = tryCount;
        }

        #endregion Sets the maximum number of retryes
        #region Do you need to try again
        public bool IsRetry()
        {
            if (RunResult || CurrentTryCount == MaxTryCount)
                return false;
            else
            {
                RunResult = true;
                return true;
            }
        }

        #endregion Do you need to try again
        #region Get the current number of retries
        public uint GetCurrentTryCount()
        {
            return CurrentTryCount + 1;
        }

        #endregion Get the current number of retries
        #region Try again
        public void RetryHandle()
        {
            RunResult = false;
            CurrentTryCount++;
        }

        #endregion Try again
        #endregion method    }

ps: Let’s look at the C# exception retry strategy through the code below

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using Polly;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace CircuitBreak_Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                var retryTwoTimesPolicy =
                     Policy
                         .Handle<DivideByZeroException>()
                         .Retry(3, (ex, count) =>
                         {
                             ("Execution failed! Number of retry times {0}", count);
                             ("The exception comes from {0}", ().Name);
                         });
                (() =>
                {
                    Compute();
                });
            }
            catch (DivideByZeroException e1)
            {
                ($"Excuted Failed,Message: ({})");

            }

            Policy policy = <TimeoutException>()
               .WaitAndRetryAsync(5, retryAttempt => (5), (exception, retryCount) =>
               {
                   //(exception);
                   string xx = "";
               });

            var result = (() => Test());


            Policy _circuitBreakerPolicy = Policy
                .Handle<HttpRequestException>()
                .Or<TimeoutRejectedException>()
                .Or<TimeoutException>()
                .CircuitBreakerAsync(
                    exceptionsAllowedBeforeBreaking: 5,
                    durationOfBreak: new TimeSpan(),
                    onBreak: (ex, breakDelay) =>
                    {
                        
                    },
                    onReset: () => { },
                    onHalfOpen: () => { }
                    );

            var fallBackPolicy =
               Policy<string>
                   .Handle<Exception>()
                   .Fallback("Execution failed, return to Fallback");

            var fallBack = (() =>
            {
                throw new Exception();
            });
            (fallBack);

           
        }

        static int Compute()
        {
            var a = 0;
            return 1 / a;
        }

        private static async Task Test()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var response = ("/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                await ();
            }
        }
    }
}

This is the end of this article about an implementation method of C# exception execution retry. For more related content on C# exception retry, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!