c#异常重试机制

     有时候咱们碰到程序异常了,想让程序继续从新执行,进行重试,这时候就须要有一个合适的方法来进行操做;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

相关文章
相关标签/搜索