March 18, 2020 11:55 by
Peter
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.
/// <summary>
/// Progressive retry for a function call.
/// </summary>
/// <param name="operation">The operation to perform.</param>
/// <param name="retryCount">The retry count (default 3).</param>
/// <param name="retryWaitMilliseconds">The retry wait milliseconds (default 100).</param>
/// <returns>System.Int32.</returns>
public static int ProgressiveRetry(Action operation, byte retryCount = 3,
int retryWaitMilliseconds = 100)
{
Encapsulation.TryValidateParam<ArgumentNullException>(operation != null);
Encapsulation.TryValidateParam<ArgumentOutOfRangeException>(retryCount > 0);
Encapsulation.TryValidateParam<ArgumentOutOfRangeException>(retryWaitMilliseconds > 0);
var attempts = 0;
do
{
try
{
attempts++;
operation();
return attempts;
}
catch (Exception ex)
{
if (attempts == retryCount)
{
throw;
}
Debug.WriteLine(ex.GetAllMessages());
Task.Delay(retryWaitMilliseconds * attempts).Wait();
}
} while (true);
}
}
Here is example code on how to use ProgressiveRetry().
var result = false;
var count = ExecutionHelper.ProgressiveRetry(() =>
{
result = NetworkHelper.IsHostAvailable("wordpress.com");
}
, retryCount: 3, retryWaitMilliseconds: 225);
Console.WriteLine($"Host available {result}. Tried call {count} times.");
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.