Created
April 16, 2021 18:24
-
-
Save randyburden/32fa86f2f4a85fbc272e7d0c951e30e1 to your computer and use it in GitHub Desktop.
Retry Helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading; | |
| namespace Helpers | |
| { | |
| /// <summary> | |
| /// Retry helpers. | |
| /// </summary> | |
| public static class RetryHelper | |
| { | |
| /// <summary> | |
| /// Retries up to the given <see cref="maxRetryCount"/> before throwing an exception. | |
| /// </summary> | |
| /// <param name="action">Action to perform.</param> | |
| /// <param name="maxRetryCount">Max retry count before throwing an exception. Default is 3.</param> | |
| /// <returns>Returns the number of retry attempts. Returns 0 if no retries were attempted.</returns> | |
| public static int Retry(Action action, int maxRetryCount = 3) | |
| { | |
| var retryCount = 0; | |
| try | |
| { | |
| action(); | |
| } | |
| catch (Exception) | |
| { | |
| retryCount++; | |
| if (retryCount >= maxRetryCount) | |
| { | |
| throw; | |
| } | |
| } | |
| return retryCount; | |
| } | |
| /// <summary> | |
| /// Retries up to the given <see cref="retryDuration"/> before throwing an exception. | |
| /// </summary> | |
| /// <param name="action">Action to perform.</param> | |
| /// <param name="retryDuration">Retry duration before throwing an exception.</param> | |
| /// <returns>Returns the number of retry attempts. Returns 0 if no retries were attempted.</returns> | |
| public static int Retry(Action action, TimeSpan retryDuration) | |
| { | |
| var retryCount = 0; | |
| var cts = new CancellationTokenSource(retryDuration); | |
| try | |
| { | |
| action(); | |
| } | |
| catch (Exception) | |
| { | |
| retryCount++; | |
| if (cts.IsCancellationRequested) | |
| { | |
| throw; | |
| } | |
| } | |
| return retryCount; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment