c#異常重試機制


     有時候我們碰到程序異常了,想讓程序繼續重新執行,進行重試,這時候就需要有一個合適的方法來進行操作;

自己寫代碼控制太麻煩了,也容易出錯。這時候當然是站在巨人的肩膀上,

https://github.com/App-vNext/Polly  Polly 一個非常好用的類庫

寫了個測試 既可以指定異常之后重試的次數,也可以之后重試的間隔時間

 1 using Polly;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using HSCP.Core;
 8 using System.Net.Http;
 9 
10 namespace polly
11 {
12     class Program
13     {
14       
15         private static void Main(string[] args)
16         {
17             //var policy = Policy.Handle<Exception>()
18             //    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2), (exception, retryCount) =>
19             //    {
20             //        NLogger.Error(exception.ToString()+"------"+ $"第{retryCount}次重試");
21 
22             //    });
23 
24 
25             var policy = Policy
26               .Handle<Exception>()
27               .RetryAsync(2, async (exception, retryCount) =>
28               {
29                   Console.WriteLine("333333:" + exception.Message + "------" + $"第{retryCount}次重試");
30               });
31 
32 
33             var result =   policy.ExecuteAsync(() => Test());
34             //string r = result.ToString();
35             Console.WriteLine("444444:");
36             Console.ReadKey();
37         }
38 
39         private static async Task Test()
40         {
41             //try
42             //{
43 
44            
45             Convert.ToInt32("w");
46             using (var httpClient = new HttpClient())
47             {
48                 var response = httpClient.GetAsync("http://news.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
49                 var  s=   await response.Content.ReadAsStringAsync();
50                 Console.WriteLine("111111:"+s);
51             }
52             //    return "url";
53             //}
54             //catch (Exception ex)
55             //{
56             //    throw new Exception();
57             //    Console.WriteLine("222222:" + ex.Message);
58             //    return null;
59             //}
60             
61           // 
62         }
63     }
64 }

 

當然還有很多不錯的功能,有興趣的話可以去看看;

目前做的保險對接業務只用到這兩個基礎的功能。

最新版本也支持core;


免責聲明!

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



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