C# by Patrik

C# Retry Pattern

The C# Retry Pattern is a coding strategy that enhances fault tolerance by automatically reattempting failed operations. Employing this pattern involves defining retry logic, such as delays between attempts, to improve the robustness and reliability of code handling transient errors.

Further Resources

...see more

This example in C# illustrates an implementation of the Retry pattern. The purpose of this method is to repeatedly attempt to execute a piece of code (referred to as the "main logic") until either the operation is successful or a specified number of retries has been reached.

public async Task RetryAsync()
{
  int retryCount = 3;
  int currentRetry = 0;

  for (;;)
  {
    try
    {
      // main logic here

      break; // Return or break.
    }
    catch (Exception ex)
    {
      currentRetry++;

      if (currentRetry > this.retryCount) throw;
    }

    await Task.Delay(TimeSpan.FromSeconds(5));
  }
}

Breakdown of the code:

  1. Initialization
  2. Infinite Loop (for (;;))
    • The method enters an infinite loop using a for loop without a condition, meaning it will continue indefinitely until explicitly broken out of.
    • Inside the loop:
      • If the main logic succeeds, the break statement is encountered, and the loop is exited.
      • If an exception occurs during the main logic execution (catch (Exception ex)), the catch block is executed.
  3. Handling Exceptions
    • currentRetry++;: Increments the currentRetry counter each time an exception is caught.
    • Checks whether the number of retries (currentRetry) has exceeded the maximum allowed retries (retryCount).
      • If the maximum retries have been reached, the exception is rethrown using throw;, propagating it further.
      • If the maximum retries have not been reached, the method proceeds to the next iteration after a delay.
  4. Delay Between Retries

Comments

Leave a Comment

All fields are required. Your email address will not be published.