解決WebClient或HttpWebRequest首次串連緩慢問題

來源:互聯網
上載者:User

【編程環境】Visual Studio 2010, NET4.0

【開發語言】C#, 理論上VB.NET等依賴.NET Framework架構的語言均受此影響

【問題描述】

使用HttpWebRequest抓取網頁內容,但首次請求總是莫名奇妙的阻塞在Request.GetResponse();上,不過一旦這次請求成功,後續的操作就很快了(如果是針對同一對象)。

相同的代碼編譯在NET3.5環境中卻一切正常,而在NET4.0環境中執行就出這問題,難道是一個BUG?

【解決方案】

在設定檔中(.config)中添加配置節:

<?xml version="1.0"?><configuration>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>  </startup>  <system.net>    <defaultProxy        enabled="false"        useDefaultCredentials="false" >      <proxy/>      <bypasslist/>      <module/>    </defaultProxy>  </system.net></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.

【總結】

問題往往出於不注意,我們要多加'小心'.

希望能幫到您!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.