HttpClient hangs when timeout is setting (Windows Phone)

╄→尐↘猪︶ㄣ 提交于 2019-12-12 10:43:54

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18231104/httpclient-hangs-when-timeout-is-setting-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!