為你的代碼加上一層重試機制


為代碼加上重試機制


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                 });

 


免責聲明!

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



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