有時候咱們碰到程序異常了,想讓程序繼續從新執行,進行重試,這時候就須要有一個合適的方法來進行操做;git
本身寫代碼控制太麻煩了,也容易出錯。這時候固然是站在巨人的肩膀上,github
https://github.com/App-vNext/Polly Polly 一個很是好用的類庫async
寫了個測試 既能夠指定異常以後重試的次數,也能夠以後重試的間隔時間測試
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 }
固然還有不少不錯的功能,有興趣的話能夠去看看;url
目前作的保險對接業務只用到這兩個基礎的功能。spa
最新版本也支持core;code