欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#異常執(zhí)行重試的實(shí)現(xiàn)方法

 更新時(shí)間:2021年08月27日 14:24:20   作者:慢慢zero  
這篇文章主要介紹了C#異常執(zhí)行重試的一種實(shí)現(xiàn)方法,重試模式可以用poll替代,通過(guò)示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下

一 模式介紹

重試模式,是應(yīng)用在異常處理中,發(fā)生異常的時(shí)候,能夠?qū)I(yè)務(wù)程序進(jìn)行重新調(diào)用,在實(shí)際中,可以使用Polly提供穩(wěn)定,簡(jiǎn)單的用法,自己實(shí)現(xiàn)主要是對(duì)模式的一種了解。

二 模式實(shí)現(xiàn)

public class RetryPattern
    {
        /**
         * 重試模式可以用Polly替代
         * 自己實(shí)現(xiàn)一種模式
         */

        #region 構(gòu)造函數(shù)

        public RetryPattern()
        {
        }

        #endregion 構(gòu)造函數(shù)

        #region 變量

        private uint MaxTryCount; // 最大重試次數(shù)
        private uint CurrentTryCount; // 當(dāng)前重試的次數(shù)
        private bool RunResult = true; // 執(zhí)行結(jié)果

        #endregion 變量

        #region 方法

        #region 設(shè)置最大重試次數(shù)

        public void SetMaxCount(uint tryCount)
        {
            // 校驗(yàn)
            if (tryCount == 0) throw new ArgumentException("重試次數(shù)不能為0");

            MaxTryCount = tryCount;
        }

        #endregion 設(shè)置最大重試次數(shù)

        #region 是否需要重試

        public bool IsRetry()
        {
            if (RunResult || CurrentTryCount == MaxTryCount)
                return false;
            else
            {
                RunResult = true;
                return true;
            }
        }

        #endregion 是否需要重試

        #region 獲取當(dāng)前重試次數(shù)

        public uint GetCurrentTryCount()
        {
            return CurrentTryCount + 1;
        }

        #endregion 獲取當(dāng)前重試次數(shù)

        #region 重試

        public void RetryHandle()
        {
            RunResult = false;
            CurrentTryCount++;
        }

        #endregion 重試

        #endregion 方法
    }

ps:下面通過(guò)代碼看下C# 異常重試策略

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Polly;
using Polly.Bulkhead;
using Polly.CircuitBreaker;
using Polly.Fallback;
using Polly.NoOp;
using Polly.Registry;
using Polly.Retry;
using Polly.Timeout;
using Polly.Utilities;
using Polly.Wrap;
using System.Net.Http;

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) =>
                         {
                             Console.WriteLine("執(zhí)行失敗! 重試次數(shù) {0}", count);
                             Console.WriteLine("異常來(lái)自 {0}", ex.GetType().Name);
                         });
                retryTwoTimesPolicy.Execute(() =>
                {
                    Compute();
                });
            }
            catch (DivideByZeroException e1)
            {
                Console.WriteLine($"Excuted Failed,Message: ({e1.Message})");

            }

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

            var result = policy.ExecuteAsync(() => 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("執(zhí)行失敗,返回Fallback");

            var fallBack = fallBackPolicy.Execute(() =>
            {
                throw new Exception();
            });
            Console.WriteLine(fallBack);

           
        }

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

        private static async Task Test()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync("http://news1.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                await response.Content.ReadAsStringAsync();
            }
        }
    }
}

到此這篇關(guān)于C#異常執(zhí)行重試的一種實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)C#異常重試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論