Progressive Retry for Network Calls

In today's mobile world, many calls across the internet or network could fail for many reasons. Some of the reasons could be the service is busy, the network is slow and many more. For these types of calls, it’s advisable to retry the call if there is an error. The current code base I am working on connects to Salesforce to retrieve and update data. Salesforce is one of those backend services that could experience these types of issues.

To help with these types of network issues, I have added a new method to my open-source code called ProgressiveRetry(). This method will try the call a given number of times. If there is an error, it will wait for a given milliseconds that increases with each error. Below is the code for this call.

  1. /// <summary>  
  2. /// Progressive retry for a function call.  
  3. /// </summary>  
  4. /// <param name="operation">The operation to perform.</param>  
  5. /// <param name="retryCount">The retry count (default 3).</param>  
  6. /// <param name="retryWaitMilliseconds">The retry wait milliseconds (default 100).</param>  
  7. /// <returns>System.Int32.</returns>  
  8. public static int ProgressiveRetry(Action operation, byte retryCount = 3,   
  9.                                    int retryWaitMilliseconds = 100)  
  10. {  
  11.     Encapsulation.TryValidateParam<ArgumentNullException>(operation != null);  
  12.     Encapsulation.TryValidateParam<ArgumentOutOfRangeException>(retryCount > 0);  
  13.     Encapsulation.TryValidateParam<ArgumentOutOfRangeException>(retryWaitMilliseconds > 0);  
  14.    
  15.     var attempts = 0;  
  16.    
  17.     do  
  18.     {  
  19.         try  
  20.         {  
  21.             attempts++;  
  22.   
  23.              operation();  
  24.             return attempts;  
  25.   
  26.         }  
  27.         catch (Exception ex)  
  28.         {  
  29.             if (attempts == retryCount)  
  30.             {  
  31.                 throw;  
  32.             }  
  33.    
  34.             Debug.WriteLine(ex.GetAllMessages());  
  35.    
  36.             Task.Delay(retryWaitMilliseconds * attempts).Wait();  
  37.                }  
  38.         } while (true);  
  39.     }  
  40. }  
Here is example code on how to use ProgressiveRetry().
  1. var result = false;  
  2. var count = ExecutionHelper.ProgressiveRetry(() =>  
  3. {  
  4.     result = NetworkHelper.IsHostAvailable("wordpress.com");  
  5. }  
  6. , retryCount: 3, retryWaitMilliseconds: 225);  
  7. Console.WriteLine($"Host available {result}. Tried call {count} times.");

Summary

The next time you are coding calls across the network, I hope you will check out this method. It is also available in the dotNetTips.Utility.Standard NuGet package. If you have any comments or questions, please make them below.