Skip to content

Instantly share code, notes, and snippets.

@prom3theu5
Created January 27, 2020 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prom3theu5/4e84edf4db2165940d4aef31be2dba48 to your computer and use it in GitHub Desktop.
Save prom3theu5/4e84edf4db2165940d4aef31be2dba48 to your computer and use it in GitHub Desktop.
RetryAfter Read Headers
private TimeSpan getServerWaitDuration(DelegateResult<HttpResponseMessage> response)
{
var retryAfter = response?.Result?.Headers?.RetryAfter;
if (retryAfter == null)
return TimeSpan.Zero;
return retryAfter.Date.HasValue
? retryAfter.Date.Value - DateTime.UtcNow
: retryAfter.Delta.GetValueOrDefault(TimeSpan.Zero);
}
var retryAfterPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r?.Headers?.RetryAfter != null) // EDIT: .Net Framework only: https://msdn.microsoft.com/en-us/library/system.net.http.headers.httpresponseheaders.aspx; not yet in this form in .NET Core?
.WaitAndRetryAsync(
retryCount: numRetries,
sleepDurationProvider: (retryCount, response, context) => getServerWaitDuration(response)
);
//Wrap with a Timeout so it doesn't run forever...
Policy timeoutPolicy = Policy.TimeoutAsync(30, TimeoutStrategy.Optimistic);
var executionPolicy = timeoutPolicy.WrapAsync(retryAfterPolicy);
//Call with below. Remember - Policies are thread safe.
/*If the code executed through the policy is your own code, the recommended pattern is to call cancellationToken.ThrowIfCancellationRequested() at suitable intervals in the cancellable work.*/
var result = await executionPolicy
.ExecuteAsync(
async ct => await httpClient.GetAsync(requestEndpoint, ct), // Execute a delegate which responds to a CancellationToken input parameter.
CancellationToken.None // CancellationToken.None here indicates you have no independent cancellation control you wish to add to the cancellation provided by TimeoutPolicy.
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment