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.
-
-
-
-
-
-
-
- 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.");
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.