解决WebClient或HttpWebRequest首次连接缓慢问题

【编程环境】Visual Studio 2010, NET4.0

【开发语言】C#, 理论上VB.NET等依赖.NET Framework框架的语言均受此影响

【问题描述】

使用HttpWebRequest抓取网页内容,但首次请求总是莫名奇妙的阻塞在Request.GetResponse();上,不过一旦这次请求成功,后续的操作就很快了(如果是针对同一对象)。

相同的代码编译在NET3.5环境中却一切正常,而在NET4.0环境中执行就出这问题,难道是一个BUG?

【解决方案】

在配置文件中(.config)中添加配置节:

  1. <?xml version="1.0"?>
  2. <configuration>
  3. <startup>
  4. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  5. </startup>
  6. <system.net>
  7. <defaultProxy
  8. enabled="false"
  9. useDefaultCredentials="false" >
  10. <proxy/>
  11. <bypasslist/>
  12. <module/>
  13. </defaultProxy>
  14. </system.net>
  15. </configuration>

【问题所在】 

.NET4.0中的默认代理是开启的,而我并没有设置!故只有等待超时后才会绕过代理,这就阻塞了.

【参考资料】

"It's not set at all in app.cong or machine.config. Hmm. If I'm reading the
MSDN docs right, the default for defaultProxy.enabled is TRUE if the element
isn't specified at all. That would be consistent with my observations.
"

http://msdn2.microsoft.com/en-us/library/kd3cf2ex(VS.80).aspx

【问题引申】

如果在其它版本的.NET环境中遇到类似问题,不妨尝试WebClient.Proxy = null;或HttpWebRequest.Proxy = null.

【总结】

问题往往出于不注意,我们要多加'小心'.

希望能帮到您!

posted @ 2011-11-13 00:46  南桥一梦  阅读(871)  评论(0编辑  收藏  举报