@@ -68,7 +68,16 @@ public static string GetSettingFromConfigOrEnvironment(string settingName)
68
68
/// <returns>A <see cref="Task"/> representing the computed backoff interval.</returns>
69
69
public static async Task DelayWithBackoffAsync ( int exponent , CancellationToken cancellationToken , TimeSpan ? unit = null , TimeSpan ? min = null , TimeSpan ? max = null )
70
70
{
71
- TimeSpan delay = ComputeBackoff ( exponent , unit , min , max ) ;
71
+ TimeSpan delay = TimeSpan . FromSeconds ( 5 ) ;
72
+
73
+ try
74
+ {
75
+ delay = ComputeBackoff ( exponent , unit , min , max ) ;
76
+ }
77
+ catch ( Exception )
78
+ {
79
+ // Use the default if there is any problem computing backoff
80
+ }
72
81
73
82
if ( delay . TotalMilliseconds > 0 )
74
83
{
@@ -85,12 +94,27 @@ public static async Task DelayWithBackoffAsync(int exponent, CancellationToken c
85
94
86
95
internal static TimeSpan ComputeBackoff ( int exponent , TimeSpan ? unit = null , TimeSpan ? min = null , TimeSpan ? max = null )
87
96
{
97
+ TimeSpan maxValue = max ?? TimeSpan . MaxValue ;
98
+
99
+ // prevent an OverflowException
100
+ if ( exponent >= 64 )
101
+ {
102
+ return maxValue ;
103
+ }
104
+
88
105
// determine the exponential backoff factor
89
106
long backoffFactor = Convert . ToInt64 ( ( Math . Pow ( 2 , exponent ) - 1 ) / 2 ) ;
90
107
91
108
// compute the backoff delay
92
109
unit = unit ?? TimeSpan . FromSeconds ( 1 ) ;
93
110
long totalDelayTicks = backoffFactor * unit . Value . Ticks ;
111
+
112
+ // If we've overflowed long, return max.
113
+ if ( backoffFactor > 0 && totalDelayTicks <= 0 )
114
+ {
115
+ return maxValue ;
116
+ }
117
+
94
118
TimeSpan delay = TimeSpan . FromTicks ( totalDelayTicks ) ;
95
119
96
120
// apply minimum restriction
@@ -100,9 +124,9 @@ internal static TimeSpan ComputeBackoff(int exponent, TimeSpan? unit = null, Tim
100
124
}
101
125
102
126
// apply maximum restriction
103
- if ( max . HasValue && delay > max )
127
+ if ( delay > maxValue )
104
128
{
105
- delay = max . Value ;
129
+ delay = maxValue ;
106
130
}
107
131
108
132
return delay ;
0 commit comments