1. 程式人生 > >C# http 效能優化500毫秒到 60 毫秒

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

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

作為有責任感的 碼農。這個 必須優化。。

後來 整理 各種方法做了優化 

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 請求,所以 這個屬性可以以適當增大。


Proxy 屬性在 .Net 4.0 時應該在 config 檔案中增加:

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

 

其他版本.NET 可以設定為null。
原因:NET4.0或3.5中的預設代理是開啟的,而我並沒有設定!故只有等待超時後才會繞過代理,這就阻塞了.其他的可以自己百度。到這了 http 的響應速度由原來 的500ms 減小的60ms,但還是 比不上Chrome。希望在以後有更好的辦法加快。晚了洗洗睡了。