
Problem
Solution
Submissions
Retry Mechanism
Certification: Intermediate Level
Accuracy: 100%
Submissions: 3
Points: 15
Write a C# program to implement a retry mechanism that will attempt to execute a method multiple times until it succeeds or reaches a maximum number of attempts. Create a RetryExecutor class that handles automatic retries when exceptions occur.
Example 1
- Input: Create retry executor with 3 max attempts and 1 second delay, define an operation that sometimes fails randomly, execute with retry
- Output: Success after multiple attempts or failure after exhausting all attempts
- Explanation:
- Step 1: Create a RetryExecutor with maximum 3 attempts and 1 second fixed delay.
- Step 2: Define a delegate operation that has a random chance of failing.
- Step 3: Execute the operation through the retry executor.
- Step 4: If the operation fails, the executor waits for 1 second and tries again.
- Step 5: Each attempt and its result are logged.
- Step 6: Either return success result or throw exception after all attempts fail.
Example 2
- Input: Create retry executor with 4 max attempts and exponential backoff, define an operation that always fails, execute with retry and exception handling
- Output: All retry attempts fail with increasing delays between attempts
- Explanation:
- Step 1: Create a RetryExecutor with maximum 4 attempts and exponential backoff.
- Step 2: Define a delegate operation that always throws an exception.
- Step 3: Execute the operation through the retry executor.
- Step 4: The operation fails on the first attempt.
- Step 5: Executor waits for 1 second (first retry delay) and tries again.
- Step 6: Operation fails again, executor waits for 2 seconds (doubled delay) and retries.
- Step 7: Operation fails again, executor waits for 4 seconds (doubled again) and retries.
- Step 8: After all attempts fail, a comprehensive exception is thrown with information about all failures.
Constraints
- Support for different types of operations (with different return types)
- Proper handling of different exception types
- Time Complexity: O(n) where n is the number of retry attempts
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use generics to support operations with different return types
- Implement exponential backoff by doubling the delay after each retry
- Use Thread.Sleep or Task.Delay for implementing the delay between retries
- Track the current attempt number and last exception for detailed error reporting
- Consider supporting async operations with Task-based method signatures