我正在尝试为 Windows Phone 应用程序中的 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 获取结果?
最佳答案
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 指出,5 秒甚至不足以完成 DNS 查询。
我建议也删除超时并让它成为默认值,因为据我所知,“检查”任务是否未停止的唯一方法是假设如果您对服务器执行 ping 操作并且它回复连接是仍然“正常”并且正在工作/下载您的文件。
关于c# - 设置超时时 HttpClient 挂起 (Windows Phone),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231104/