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 client sandbox on 'http://ptsv2.com/t/v98pb-1521637251/post' (you can visit this link "http://ptsv2.com/t/v98pb-1521637251" to see the configuration or make yourself a "toilet"):
class Program
{
private static readonly HttpClient _httpClient = new HttpClient()
; //WHY? BECAUSE - https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
static void Main(string[] args)
{
_httpClient.BaseAddress = new Uri(@"http://ptsv2.com/t/v98pb-1521637251/post");
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
var result = ExecuteAsync("Test").Result;
Console.WriteLine(result);
Console.ReadLine();
}
private static async Task<string> ExecuteAsync(string request)
{
var response = await Policies.PolicyWrap.ExecuteAsync(async () => await _httpClient.PostAsync("", new StringContent(request)).ConfigureAwait(false));
if (!response.IsSuccessStatusCode)
return "Unsuccessful";
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
The Http client waits for 4 seconds, then returns the response.
I have set up my Policies like this (timeout policy is set up to wait for 1 second for the response):
public static class Policies
{
public static TimeoutPolicy<HttpResponseMessage> TimeoutPolicy
{
get
{
return Policy.TimeoutAsync<HttpResponseMessage>(1, onTimeoutAsync: (context, timeSpan, task) =>
{
Console.WriteLine("Timeout delegate fired after " + timeSpan.TotalMilliseconds);
return Task.CompletedTask;
});
}
}
public static RetryPolicy<HttpResponseMessage> RetryPolicy
{
get
{
return Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.Or<TimeoutRejectedException>()
.RetryAsync(3, onRetryAsync: (delegateResult, i) =>
{
Console.WriteLine("Retry delegate fired for time No. " + i);
return Task.CompletedTask;
});
}
}
public static FallbackPolicy<HttpResponseMessage> FallbackPolicy
{
get
{
return Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.Or<TimeoutRejectedException>()
.FallbackAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError), onFallbackAsync: (delegateResult, context) =>
{
Console.WriteLine("Fallback delegate fired");
return Task.CompletedTask;
});
}
}
public static PolicyWrap<HttpResponseMessage> PolicyWrap
{
get
{
return Policy.WrapAsync(FallbackPolicy, RetryPolicy, TimeoutPolicy);
}
}
}
However, onTimeoutAsync delegate is not being hit at all and the console prints out the following:
Retry delegate fired for time No. 1 //Hit after 4 seconds
Retry delegate fired for time No. 2 //Hit after 4 more seconds
Retry delegate fired for time No. 3 //Hit after 4 more seconds
Fallback delegate fired
Unsuccessful
It is included in the PolicyWrap and is Async and I do not know why it is not being hit. Any information is highly appreciated.
Polly Timeout policy with the default
TimeoutStrategy.Optimistic
operates by timing-outCancellationToken
, 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:
Polly async executions by default do not continue on captured synchronization context (they execute with
.ConfigureAwait(false)
), so this can also be shortened to: