C# http 性能優化500毫秒到 60 毫秒

偶然發現 C# 的 HttpRequest 要比 Chrome 請求同一Url 慢好多。C# HttpRequest 要500毫秒 而Chrome 只須要 39ms。服務器

做爲有責任感的 碼農。這個 必須優化。。併發

後來 整理 各類方法作了優化 tcp

HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;

request.ServicePoint.UseNagleAlgorithm = false;
request.ServicePoint.ConnectionLimit = 65500;
request.AllowWriteStreamBuffering = false; 
request.Proxy = null;
response.Close();
request.Abort();

 


打開 KeepAlive 屬性,這個能夠打開一個tcp鏈接並在 一段時內重用tcp鏈接,從而加快http 請求。(默認是打開的)(我在開啓keepalive 時出現 服務器關閉鏈接的錯誤,在請求完成後 加response.Close();request.Abort(); 後 錯誤消失)
Expect100Continue  的做用優化

發送一個請求, 包含一個Expect:100-continue, 詢問Server使用願意接受數據
接收到Server返回的100-continue應答之後, 才把數據POST給Server
因此關閉它能夠加快http 請求。
還有 ConnectionLimit 默認是2 ,就是說 系統 只能 併發 2個http 請求,因此 這個屬性能夠以適當增大。spa


Proxy 屬性在 .Net 4.0 時應該在 config 文件中增長:.net

<system.net>
<defaultProxy
enabled="false"
useDefaultCredentials="false" >
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
</configuration>

 

其餘版本.NET 能夠設置爲null。
緣由:NET4.0或3.5中的默認代理是開啓的,而我並無設置!故只有等待超時後纔會繞過代理,這就阻塞了.其餘的能夠本身百度。到這了 http 的響應速度由原來 的500ms 減少的60ms,但仍是 比不上Chrome。但願在之後有更好的辦法加快。晚了洗洗睡了。代理

相關文章
相關標籤/搜索