Last active
February 7, 2018 16:23
-
-
Save abdallaadelessa/bd0508d7cdfb9ea268b213fcaaf23308 to your computer and use it in GitHub Desktop.
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
public static class TaskRetryExtension | |
{ | |
public static readonly IRetryPolicy DefaultRetryPolicy = new FibonacciRetryPolicy(); | |
public static Task<T> WithRetry<T>(this Task<T> task, int maxNumOfRetries, CancellationToken token) | |
{ | |
return RetryTask(task, 0, maxNumOfRetries, token, DefaultRetryPolicy); | |
} | |
public static Task<T> WithRetry<T>(this Task<T> task, int maxNumOfRetries, CancellationToken token, IRetryPolicy retryPolicy) | |
{ | |
return RetryTask(task, 0, maxNumOfRetries, token, retryPolicy); | |
} | |
public interface IRetryPolicy | |
{ | |
int GetWaitTime(int currentRetryNum); | |
} | |
private class FibonacciRetryPolicy : IRetryPolicy | |
{ | |
public int GetWaitTime(int n) | |
{ | |
if (n <= 1) return n; | |
else return GetWaitTime(n - 1) + GetWaitTime(n - 2); | |
} | |
} | |
#region Main | |
private async static Task<T> RetryTask<T>(Task<T> task, int currentRetryNum, int maxNumOfRetries, CancellationToken token, IRetryPolicy retryPolicy) | |
{ | |
try | |
{ | |
await Task.Delay((retryPolicy.GetWaitTime(currentRetryNum) * 1000), token); | |
return await task; | |
} | |
catch (Exception ex) | |
{ | |
if (currentRetryNum < maxNumOfRetries && !token.IsCancellationRequested) | |
{ | |
return await RetryTask(task, ++currentRetryNum, maxNumOfRetries, token, retryPolicy); | |
} | |
else | |
{ | |
throw ex; | |
} | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment