.NET/C#程序開發中如何更優美地實現失敗任務重試的邏輯?


背景

 在.NET中,異常是指成員沒有完成它的名稱宣稱可以完成的行動。在異常的機制中,異常和某件事情的發生頻率無關。有時候需要對一些失敗的任務進行多次的重試,如果重試的次數達到我們設定的閥值,則再放棄任務。

解決方案

使用一個靜態類和靜態的泛型方法來處理,創建通用的任務重試機制,我們可以使用Action作為參數。

實現方法

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>
        /// 若發生 Exception (資料庫查詢逾時),重複執行相同動作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="handler"></param>
        /// <param name="retryTimes">預設重試 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($"剩餘重試次數: {retryTimes}, retry error: {e.Message}, Exception detail: {e.ToJsonString()}");
                System.Threading.Thread.Sleep(sleepMillisecondsTimeout);
                return Retry(handler, retryTimes);
            }
        }

        /// <summary>
        /// 傳入多個動作,遇到 Exception依序執行 (資料庫查詢逾時,改用不同條件查詢)
        /// </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}次執行錯誤(start from 0): retry error: {e.Message}, Exception detail: {e.ToJsonString()}");
                    System.Threading.Thread.Sleep(sleepMillisecondsTimeout);
                }
            }
            return default(T);
        }

        /// <summary>
        /// 若發生 Exception (資料庫查詢逾時),重複執行相同動作
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="retryTimes">預設重試 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($"剩餘重試次數: {retryTimes}, retry error: {e.Message}, Exception detail: {e.ToJsonString()}");
                System.Threading.Thread.Sleep(sleepMillisecondsTimeout);
                Retry(handler, retryTimes);
            }
        }

    }
}

調用方法

調用方法如下:

 public List<SystemMailModel> GetSendMailList(SystemMailSearchModel mailSearchModel)
        {
            return Common.CommonTools.Retry(() => _spSystemSettingsDapperRep.GetSendMailList(mailSearchModel));
        }

當然,你也可以自己重載一個async的異步方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM