C#异常执行重试的实现方法
时间:2021-12-26 10:41:57|栏目:.NET代码|点击: 次
一 模式介绍
重试模式,是应用在异常处理中,发生异常的时候,能够对业务程序进行重新调用,在实际中,可以使用Polly提供稳定,简单的用法,自己实现主要是对模式的一种了解。
二 模式实现
public class RetryPattern { /** * 重试模式可以用Polly替代 * 自己实现一种模式 */ #region 构造函数 public RetryPattern() { } #endregion 构造函数 #region 变量 private uint MaxTryCount; // 最大重试次数 private uint CurrentTryCount; // 当前重试的次数 private bool RunResult = true; // 执行结果 #endregion 变量 #region 方法 #region 设置最大重试次数 public void SetMaxCount(uint tryCount) { // 校验 if (tryCount == 0) throw new ArgumentException("重试次数不能为0"); MaxTryCount = tryCount; } #endregion 设置最大重试次数 #region 是否需要重试 public bool IsRetry() { if (RunResult || CurrentTryCount == MaxTryCount) return false; else { RunResult = true; return true; } } #endregion 是否需要重试 #region 获取当前重试次数 public uint GetCurrentTryCount() { return CurrentTryCount + 1; } #endregion 获取当前重试次数 #region 重试 public void RetryHandle() { RunResult = false; CurrentTryCount++; } #endregion 重试 #endregion 方法 }
ps:下面通过代码看下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("执行失败! 重试次数 {0}", count); Console.WriteLine("异常来自 {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("执行失败,返回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(); } } } }