Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient hangs when timeout is setting (Windows Phone)

I'm trying to set timeout to HttpClient object in Windows Phone App. But if request is not completed before timeout, GetAsync never returns a value.

I'm using the following code to get 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 can I properly set the timeout to get result from GetAsync?

like image 868
Mikhail Kamenev Avatar asked Aug 14 '13 11:08

Mikhail Kamenev


2 Answers

Taken from HttpClient documentation:

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

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

and as ZombieSheep notes 5 seconds are not enough even for a DNS query to complete.

I would suggest removing the timeout as well and let it to is default value, since from what I know the only way to "check" if task didnt stop is by assuming that if you ping the server and it replies the connection is still "OK" and working/downloading your file.

like image 99
George Nikolaides Avatar answered Sep 20 '22 01:09

George Nikolaides


Without going and writing code to check, here are some likely culprits.

1) Your 5 second timeout is not long enough to download the full file "boo.mp3", so the timeout stops the operation.
2) Your web server is taking too long to respond (unlikely, but possible over a mobile network)

It might be best to either remove the timeout value altogether, or set it to a more realistic value.

like image 25
ZombieSheep Avatar answered Sep 19 '22 01:09

ZombieSheep