我正在尝试在
Windows Phone App中将超时设置为HttpClient对象.但是如果请求在超时之前没有完成,则GetAsync永远不会返回值.
我正在使用以下代码来获得响应:
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();
如何正确设置超时以从GetAsync获取结果?
解决方法
摘自
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.
并且正如ZombieSheep所说,即使DNS查询完成,5秒也不够.
我建议删除超时并让它为默认值,因为从我所知道的“检查”任务没有停止的唯一方法是假设如果你ping服务器并且它回复连接仍然是“好的” “并且正在处理/下载您的文件.