C#異常執(zhí)行重試的實(shí)現(xiàn)方法
一 模式介紹
重試模式,是應(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)文章
c# 在windows中操作IIS設(shè)置FTP服務(wù)器的示例
這篇文章主要介紹了c# 在windows中操作IIS設(shè)置FTP服務(wù)器的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03C#模板方法模式(Template Method Pattern)實(shí)例教程
這篇文章主要介紹了C#模板方法模式(Template Method Pattern),以實(shí)例形式講述了C#抽象類模板方法的用法,具有很高的實(shí)用價(jià)值,需要的朋友可以參考下2014-09-09WPF使用DrawingContext實(shí)現(xiàn)二維繪圖
這篇文章介紹了WPF使用DrawingContext實(shí)現(xiàn)二維繪圖的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06C#中使用IrisSkin2.dll美化WinForm程序界面的方法
這篇文章主要介紹了c#中使用IrisSkin2.dll美化WinForm程序界面的實(shí)現(xiàn)方法,需要的朋友可以參考下2013-05-05C# 中使用NModbus4通信庫(kù)執(zhí)行寫(xiě)操作
在C#中NModbus4庫(kù)提供了一個(gè)方便的方式來(lái)與支持Modbus協(xié)議的設(shè)備進(jìn)行交互,本文就來(lái)介紹了使用NModbus4通信庫(kù)執(zhí)行寫(xiě)操作,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03