为你的代码加上一层重试机制

为代码加上重试机制


1.前言:对于经常跟网络编程打交道的你来说,并不是你的每次Request,Server都会给你想要的Response。重试机制虽然并不能解决这种情况,但是却可以大大减少这种情况的发生。

 

2.介绍下重试机制类:RetryUtil.cs

  使用了委托,代码很短,也不难理解。

 1     public class RetryUtil
 2     {
 3         public delegate void NoArgumentHandler();
 4         /// <summary>
 5         /// retry mechanism without argument
 6         /// </summary>
 7         /// <param name="retryTimes">try times</param>
 8         /// <param name="interval">time span</param>
 9         /// <param name="throwIfFail">throw exception</param>
10         /// <param name="function">function name</param>
11         public static void Retry(int retryTimes, TimeSpan interval, bool throwIfFail, NoArgumentHandler function)
12         {
13             if (function == null)
14                 return;
15 
16             for (int i = 0; i < retryTimes; ++i)
17             {
18                 try
19                 {
20                     function();
21                     break;
22                 }
23                 catch (Exception)
24                 {
25                     if (i == retryTimes - 1)
26                     {
27                         if (throwIfFail)
28                             throw;
29                         else
30                             break;
31                     }
32                     else
33                     {
34                         if (interval != null)
35                             Thread.Sleep(interval);
36                     }
37                 }
38             }
39         }
40     }
View Code

 

3.举例使用:Demon

  3.1 下载文件,如果出错重复尝试五次,每次间隔2秒,全部失败抛出异常。

1                 RetryUtil.Retry(5, TimeSpan.FromSeconds(2), true, delegate
2                 {
3                     WebClientUtil.DownloadFile(string.Format("{0}{1}", baseUrl, tdNewSeries), 30000, dexsrp);
4                 });

  3.2 搜索Outlook邮件,如果出错重复尝试五次,每次间隔2秒,全部失败抛出异常。

 1         public List<EmailMessage> GetSearchQueryEmailMessage(string mailbox, string subjectKeyword, DateTime startDate, DateTime endDate, string sendAddress = "", string mailFolderPath = @"Inbox", string bodyKeyword = "")
 2         {
 3             List<EmailMessage> emails = null;
 4             this.query = new EWSMailSearchQuery(sendAddress, mailbox, mailFolderPath, subjectKeyword, bodyKeyword, startDate, endDate);
 5 
 6             RetryUtil.Retry(5, TimeSpan.FromSeconds(2), true, delegate
 7             {
 8                 emails = EWSMailSearchQuery.SearchMail(service, query);
 9             });
10 
11             return emails;
12         }

  3.3 访问网页,如果出错重复尝试五次,每次间隔2秒,全部失败抛出异常。

1                 RetryUtil.Retry(5, TimeSpan.FromSeconds(2), true, delegate
2                 {
3                     htc = WebClientUtil.GetHtmlDocument(sourceUrl, 3000);
4                 });

 

posted @ 2014-09-29 14:43  TRHFC  阅读(2128)  评论(6编辑  收藏  举报