HttpClient freezes when setting timeout (Windows Phone)

I am trying to set a timeout on an HttpClient object in a Windows Phone application. But if the request is not completed before the timeout expires, GetAsync never returns a value.

I use the following code to get a response:

 HttpClientHandler handler = new HttpClientHandler(); HttpClient client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(5); client.BaseAddress = new Uri("http://www.foo.com"); HttpResponseMessage response = await client.GetAsync("/boo.mp3");//<--Hangs byte[] data = await response.Content.ReadAsByteArrayAsync(); 

How to set the timeout to get the result from GetAsync?

+6
source share
2 answers

Taken from the HttpClient documentation :

The default value is 100,000 milliseconds (100 seconds).

A Domain Name System (DNS) query can take up to 15 seconds or a timeout. If your request contains a host name that requires and you set Timeout to less than 15 seconds, it may take 15 seconds or more before WebException is sent to indicate a timeout for your request.

and as ZombieSheep notes, 5 seconds is not enough even to complete the DNS query.

I would also suggest deleting the timeout, and let this be the default value, since from what I know, the only way to "check" if the task did not stop is to assume that if you pinged the server, and it is responsible for connection, still OK and working / uploading file.

+8
source

Without going over and writing down code for verification, here are some of the possible culprits.

1) Your 5 second timeout is not long enough to load the complete file "boo.mp3", so the timeout stops the operation.
2) Your web server has been reacting for too long (unlikely, but possible over a mobile network).

It is best to either remove the timeout value as a whole, or set its more realistic value.

+2
source

Source: https://habr.com/ru/post/951713/


All Articles