简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM