Successfully added
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
- Retry pattern - Azure Architecture Center | Microsoft Learn
- Build resilient HTTP apps: Key development patterns - .NET | Microsoft Learn
- How to Implement Retry Logic in C# - Code Maze (code-maze.com)
- How to Implement Effective Retry Logic in C# | by Dev·edium | Medium
- Retry Pattern — a Not so Naive Approach | by Yini Yin | Medium
...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:
- Initialization
- 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.
- The method enters an infinite loop using a
- Handling Exceptions
currentRetry++;
: Increments thecurrentRetry
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.
- If the maximum retries have been reached, the exception is rethrown using
- Delay Between Retries
Referenced in:
Comments