有时候我们碰到程序异常了,想让程序继续重新执行,进行重试,这时候就需要有一个合适的方法来进行操作;
自己写代码控制太麻烦了,也容易出错。这时候当然是站在巨人的肩膀上,
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。