• 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();
                }
            }
        }
    }
  • 相关阅读:
    Facebook – Facebook Page Embed
    HTML & CSS – Styling List
    json转换struct结构体
    ICLR 2022 | 阿里提出目标检测新范式GiraffeDet:轻骨干、重Neck
    cuda10.1+cudnn7.5.0+tensorrt5.1
    cuda加速第一个例子
    卡尔曼滤波的原理(Python实现)
    CUDA入门(一):CUDA11.0+VS2019+WIN10环境配置
    匹配 基于深度学习实现以图搜图功能
    标注>>分割半自动
  • 原文地址:https://www.cnblogs.com/qingfenglin/p/13731415.html
Copyright © 2020-2023  润新知