c# – HttpClient在设置超时时挂起(Windows Phone)

前端之家收集整理的这篇文章主要介绍了c# – HttpClient在设置超时时挂起(Windows Phone)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在 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服务器并且它回复连接仍然是“好的” “并且正在处理/下载您的文件.

原文链接:https://www.f2er.com/csharp/92529.html

猜你在找的C#相关文章