.NET/C#程序开发中如何更优美地实现失败任务重试的逻辑?
生活随笔
收集整理的這篇文章主要介紹了
.NET/C#程序开发中如何更优美地实现失败任务重试的逻辑?
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
背景
?在.NET中,異常是指成員沒(méi)有完成它的名稱宣稱可以完成的行動(dòng)。在異常的機(jī)制中,異常和某件事情的發(fā)生頻率無(wú)關(guān)。有時(shí)候需要對(duì)一些失敗的任務(wù)進(jìn)行多次的重試,如果重試的次數(shù)達(dá)到我們?cè)O(shè)定的閥值,則再放棄任務(wù)。
解決方案
使用一個(gè)靜態(tài)類和靜態(tài)的泛型方法來(lái)處理,創(chuàng)建通用的任務(wù)重試機(jī)制,我們可以使用Action作為參數(shù)。
實(shí)現(xiàn)方法
using BQoolCommon.Service.ExtensionMethod; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks;namespace BQoolCommon.Service.Common {public static class CommonTools{static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();static int sleepMillisecondsTimeout = 1000;/// <summary>/// 若發(fā)生 Exception (資料庫(kù)查詢逾時(shí)),重複執(zhí)行相同動(dòng)作/// </summary>/// <typeparam name="T"></typeparam>/// <param name="handler"></param>/// <param name="retryTimes">預(yù)設(shè)重試 3次,傳入 0直接 return default(T)</param>/// <returns></returns>public static T Retry<T>(Func<T> handler, int retryTimes = 3){if (retryTimes <= 0){return default(T);}try{return handler();}catch (Exception e){retryTimes--;logger.Error($"剩餘重試次數(shù): {retryTimes}, retry error: {e.Message}, Exception detail: {e.ToJsonString()}");System.Threading.Thread.Sleep(sleepMillisecondsTimeout);return Retry(handler, retryTimes);}}/// <summary>/// 傳入多個(gè)動(dòng)作,遇到 Exception依序執(zhí)行 (資料庫(kù)查詢逾時(shí),改用不同條件查詢)/// </summary>/// <typeparam name="T"></typeparam>/// <param name="handlers"></param>/// <returns></returns>public static T Retry<T>(params Func<T>[] handlers){for (int i = 0; i < handlers.Length; i++){var handler = handlers[i];try{return handler();}catch (Exception e){logger.Error($"第 {i}次執(zhí)行錯(cuò)誤(start from 0): retry error: {e.Message}, Exception detail: {e.ToJsonString()}");System.Threading.Thread.Sleep(sleepMillisecondsTimeout);}}return default(T);}/// <summary>/// 若發(fā)生 Exception (資料庫(kù)查詢逾時(shí)),重複執(zhí)行相同動(dòng)作/// </summary>/// <param name="handler"></param>/// <param name="retryTimes">預(yù)設(shè)重試 3次,傳入 0直接 return</param>public static void Retry(Action handler, int retryTimes = 3){if (retryTimes <= 0){return;}try{handler();}catch (Exception e){retryTimes--;logger.Error($"剩餘重試次數(shù): {retryTimes}, retry error: {e.Message}, Exception detail: {e.ToJsonString()}");System.Threading.Thread.Sleep(sleepMillisecondsTimeout);Retry(handler, retryTimes);}}} }調(diào)用方法
調(diào)用方法如下:
public List<SystemMailModel> GetSendMailList(SystemMailSearchModel mailSearchModel){return Common.CommonTools.Retry(() => _spSystemSettingsDapperRep.GetSendMailList(mailSearchModel));}當(dāng)然,你也可以自己重載一個(gè)async的異步方法。
總結(jié)
以上是生活随笔為你收集整理的.NET/C#程序开发中如何更优美地实现失败任务重试的逻辑?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Git】Git-常用命令备忘录(二)
- 下一篇: c# char unsigned_dll