C#異常執(zhí)行重試的實現(xiàn)方法
一 模式介紹
重試模式,是應用在異常處理中,發(fā)生異常的時候,能夠?qū)I(yè)務程序進行重新調(diào)用,在實際中,可以使用Polly提供穩(wěn)定,簡單的用法,自己實現(xiàn)主要是對模式的一種了解。
二 模式實現(xiàn)
public class RetryPattern
{
/**
* 重試模式可以用Polly替代
* 自己實現(xiàn)一種模式
*/
#region 構(gòu)造函數(shù)
public RetryPattern()
{
}
#endregion 構(gòu)造函數(shù)
#region 變量
private uint MaxTryCount; // 最大重試次數(shù)
private uint CurrentTryCount; // 當前重試的次數(shù)
private bool RunResult = true; // 執(zhí)行結(jié)果
#endregion 變量
#region 方法
#region 設(shè)置最大重試次數(shù)
public void SetMaxCount(uint tryCount)
{
// 校驗
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 獲取當前重試次數(shù)
public uint GetCurrentTryCount()
{
return CurrentTryCount + 1;
}
#endregion 獲取當前重試次數(shù)
#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("執(zhí)行失敗! 重試次數(shù) {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("執(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í)行重試的一種實現(xiàn)方法的文章就介紹到這了,更多相關(guān)C#異常重試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c# 在windows中操作IIS設(shè)置FTP服務器的示例
這篇文章主要介紹了c# 在windows中操作IIS設(shè)置FTP服務器的示例,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-03-03
C#模板方法模式(Template Method Pattern)實例教程
這篇文章主要介紹了C#模板方法模式(Template Method Pattern),以實例形式講述了C#抽象類模板方法的用法,具有很高的實用價值,需要的朋友可以參考下2014-09-09
WPF使用DrawingContext實現(xiàn)二維繪圖
這篇文章介紹了WPF使用DrawingContext實現(xiàn)二維繪圖的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06
C#中使用IrisSkin2.dll美化WinForm程序界面的方法
這篇文章主要介紹了c#中使用IrisSkin2.dll美化WinForm程序界面的實現(xiàn)方法,需要的朋友可以參考下2013-05-05

