I have several methods that require an internet connection. If the connection fails, I want to repeat the method for a period of time before the failure. Since the application can happily continue to work in anticipation of a successful response, I want to do this asynchronously.
I am using Polly (5.3.1) to implement asynchronous repeat logic using Tasks
.
I simulate a disconnect by starting a process with Wi-Fi turned off and turning it on while re-viewing. I expected that after turning on my connection again, the method will be successful, if I try again, what I see is that the method continues to return HttpRequestException
as if the connection was suspended until the repetition completes, and in which he gives the moment to the caller.
If I run the method with Wi-Fi turned on as usual, it will succeed right away.
public async Task<string> GetHtmlAsync(string url)
{
using (var client = new HttpClient())
using (var response = await client.GetAsync(url))
{
response.EnsureSuccessStatusCode();
using (var content = response.Content)
{
return await content.ReadAsStringAsync();
}
}
}
public async Task<TResult> RetryAsync<TResult, TException>(Task<TResult> task, int retries, int seconds) where TException : Exception
{
return await Policy
.Handle<TException>()
.WaitAndRetryAsync(retries, wait => TimeSpan.FromSeconds(seconds))
.ExecuteAsync(async () => await task);
}
var html = await RetryAsync<string, HttpRequestException>(GetHtmlAsync("https://www.google.co.uk"), 12, 5);
Why does the method continue to fail, even though my connection is up and running during subsequent attempts?
source
share