i'm facing whit httpclient and timeout configuration. After doing a lot of googling i got on these conclussions:
- Http client timeout is fine only once i connect to an avaiable host/server.
- If Host is unavaiable or server is down, HttpClient.Timeout does not matter and i'm getting a TaskCancelledException wrapping SocketException (connection refused) after about 80seconds.
I learn httpClient timeout works only after the server recieves the request, so, if host/server is down, i get so longs timeouts related to sockets.
I need to configure a more "wide" timeout for my httpClient getAsync, postAsync... requests, and stop the operation at the specified amount of time regarless the server is avaiable or not.
I cant figure out what i could do to control timeour effectively, that stackoverflow thread (link), suggest task calcellation approach on this manner:
var timeout = Task.Delay(10000); // 10 seconds timeout
var request = httpClient.GetAsync("http://www.google.com");
await Task.WhenAny(timeout, request); // wait for either timeout or the request
if (timeout.IsCompleted) // if the timeout ended first, then handle it
{
// handle timeout
}
// otherwise continue processing the request result
var response = await request;
While that might work i will lost the socket exception and offers poor control. Because, in short, what i'm trying to do is find a way to set a timeout for resolution/connection to the server (about 2 seconds), and higher timeout for waiting the response once connection is stablished to the server.
It makes senses for me because my web server is accesed througt local network, so, 2 seconds is more than enought to get the conclusion of "server unavaiable", but once the server start processing the response i need a bigger timeout for waiting response.
Thanks in advance.