C#异常执行重试的实现方法
作者:慢慢zero 时间:2023-12-04 16:24:59
一 模式介绍
重试模式,是应用在异常处理中,发生异常的时候,能够对业务程序进行重新调用,在实际中,可以使用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();
}
}
}
}
来源:https://www.cnblogs.com/slowzero/p/15193522.html
标签:C#,异常重试
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java 继承与多态的深入理解
2023-10-05 04:25:41
Java如何跳过https的ssl证书验证详解
2023-08-24 11:34:56
![](https://img.aspxhome.com/file/2023/4/58094_0s.jpg)
Java中的接口多继承机制
2023-08-28 06:13:48
![](https://img.aspxhome.com/file/2023/4/79824_0s.png)
C#将Sql数据保存到Excel文件中的方法
2023-11-11 08:34:26
C#入门教程之集合ArrayList用法详解
2022-04-30 06:32:13
![](https://img.aspxhome.com/file/2023/8/119568_0s.png)
详解C#中 Thread,Task,Async/Await,IAsyncResult的那些事儿
2021-12-08 20:07:32
![](https://img.aspxhome.com/file/2023/4/129684_0s.png)
Unity3D开发实战之五子棋游戏
2023-06-01 12:25:56
![](https://img.aspxhome.com/file/2023/8/100158_0s.gif)
mybatis注入Date日期值为null的解决方法
2021-12-08 01:49:17
![](https://img.aspxhome.com/file/2023/1/70571_0s.png)
Java JVM程序指令码实例解析
2022-05-16 15:09:38
![](https://img.aspxhome.com/file/2023/6/81356_0s.png)
C#中的协变与逆变小结
2022-10-25 13:30:25
![](https://img.aspxhome.com/file/2023/7/122667_0s.png)
java 一个类实现两个接口的案例
2023-08-09 12:24:35
![](https://img.aspxhome.com/file/2023/0/58160_0s.jpg)
Android实现自动填写获取验证码功能
2023-04-17 13:47:12
java 生成xml并转为字符串的方法
2023-01-07 08:27:30
C#中out与ref的区别实例解析
2022-01-27 13:29:09
SpringBoot整合MybatisPlus实现增删改查功能
2022-10-31 05:24:15
![](https://img.aspxhome.com/file/2023/8/65728_0s.png)
C#时间戳基本用法实例分析
2022-10-12 14:22:40
C#简单快速的json组件fastJSON使用介绍
2022-08-13 01:47:50
![](https://img.aspxhome.com/file/2023/8/102288_0s.png)
android中SQLite使用及特点
2023-07-24 23:33:28
![](https://img.aspxhome.com/file/2023/5/126675_0s.png)
C#单例模式(Singleton Pattern)详解
2021-12-30 05:55:03
详解Android Activity之间跳转出现短暂黑屏的处理方法
2021-06-28 04:44:03