简体   繁体   English

设置超时时HttpClient挂起(Windows Phone)

[英]HttpClient hangs when timeout is setting (Windows Phone)

I'm trying to set timeout to HttpClient object in Windows Phone App. 我正在尝试在Windows Phone App中将超时设置为HttpClient对象。 But if request is not completed before timeout, GetAsync never returns a value. 但是如果请求在超时之前没有完成,则GetAsync永远不会返回值。

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? 如何正确设置超时以从GetAsync获取结果?

Taken from HttpClient documentation : 取自HttpClient文档

The default value is 100,000 milliseconds (100 seconds). 默认值为100,000毫秒(100秒)。

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. 域名系统(DNS)查询最多可能需要15秒才能返回或超时。 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. 如果您的请求包含需要解析的主机名,并且您将Timeout设置为小于15秒的值,则可能需要15秒或更长时间才能引发WebException以指示请求超时。

and as ZombieSheep notes 5 seconds are not enough even for a DNS query to complete. 并且正如ZombieSheep所说,即使DNS查询完成,5秒也不够。

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. 我建议删除超时并让它为默认值,因为从我所知道的“检查”任务没有停止的唯一方法是假设如果你ping服务器并且它回复连接仍然是“好的” “并且正在处理/下载您的文件。

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. 1)您的5秒超时不足以下载完整文件“boo.mp3”,因此超时会停止操作。
2) Your web server is taking too long to respond (unlikely, but possible over a mobile network) 2)您的Web服务器响应时间太长(不太可能,但可能通过移动网络)

It might be best to either remove the timeout value altogether, or set it to a more realistic value. 最好是完全删除超时值,或将其设置为更实际的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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