This is a FULLY working example (Copy/paste it and play around, just get the Polly Nuget)
I have the following Console app code which makes a POST request to an HTTP cli
Polly Timeout policy with the default TimeoutStrategy.Optimistic
operates by timing-out CancellationToken
, so the delegates you execute must respond to co-operative cancellation. See the Polly Timeout wiki for more detail.
Changing your execution line to the following should make the timeout work:
var response = await Policies.PolicyWrap.ExecuteAsync(
async ct => await _httpClient.PostAsync(/* uri */, new StringContent(request), ct).ConfigureAwait(false),
CancellationToken.None // CancellationToken.None here indicates you have no independent cancellation control you wish to add to the cancellation provided by TimeoutPolicy. You can also pass in your own independent CancellationToken.
);
Polly async executions by default do not continue on captured synchronization context (they execute with .ConfigureAwait(false)
), so this can also be shortened to:
var response = await Policies.PolicyWrap.ExecuteAsync(
ct => _httpClient.PostAsync(/* uri */, new StringContent(request), ct),
CancellationToken.None
);