C#(.NET),如何修复Web响应性能,耗费太多时间

时间:2017-02-04 14:18:28

标签: c# html .net http httpwebresponse

我需要优化我的代码,响应时间为1秒,ReadToEnd的经过时间() - 0.5秒,所有其他代码(完整网络请求)仅需0.1秒。

request2.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

//This 1sec+
HttpWebResponse response = (HttpWebResponse)request2.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

//This 0.5sec+
string mem = sr.ReadToEnd();
sr.Close();  

P.S:Html代码约200k +字符,但我只需要4-5。

4 个答案:

答案 0 :(得分:2)

最有可能的是,未设置HttpWebResponse的代理设置会导致延迟。始终建议设置代理,即使它未使用。另请尝试使用using子句:

request2.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

request2.Proxy = null;
using (HttpWebResponse response = (HttpWebResponse)request2.GetResponse())
{
    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    string mem = sr.ReadToEnd();
}

答案 1 :(得分:2)

初始GetResponse调用生成安全协商,Get和excecute,然后是HTTP响应,其前几个字节包含Http响应代码(200,500,404等)。

您的客户端Http缓冲区可能已经收到了响应的正文,或者仍然正在流入它 - 您无法真正说出来。您的第二个调用(readToEnd)读取接收缓冲区中的所有字节,并等待服务器发送Http Header中指示的所有字节。

您的代码不太可能对Web服务调用的执行时间造成任何可观的成本,并且我看不到任何可能的验证步骤 - 您需要确定在没有客户端代码的情况下调用的时间。< / p>

使用Telerik Fiddler跟踪从目标Web服务调用的字节数,以及从服务器到客户端的原始传输时间 - 只需在Fiddler或Web浏览器中调用URL即可。这将隔离您的代码,服务器或连接延迟是否耗费时间。

答案 2 :(得分:0)

检查你的js脚本不依赖于其他服务,存储库等。在我的项目之前它曾经为我工作过。下载它们并将其移动到本地文件夹

答案 3 :(得分:0)

要添加其他使用usingsetting proxy to null的建议,您可能还想尝试只读取特定数量的字符,而不是阅读所有内容。

var content = new char[10];
sr.Read(content, 0, content.Length);
string contentStr = new String(content);
相关问题