简体   繁体   English

WebRequests很慢(需要4秒)我如何加快速度?

[英]WebRequests are slow (taking 4 seconds) how do I speed them up?

I'm doing a web request that is too slow. 我正在做一个太慢的网络请求。 It takes around 3.2 seconds to GetResponseStream() and .8 seconds to ReadToEnd() GetResponseStream()需要大约3.2秒,ReadToEnd()需要0.8秒

If I run the same request in a web browser I get a response in less than a second... I'm wondering what I can do to speed up the request and what might cause it to be slow? 如果我在网络浏览器中运行相同的请求,我会在不到一秒的时间内收到响应......我想知道我能做些什么来加快请求速度以及可能导致速度变慢的原因?

Based on other questions I saw here, I disabled the proxy in app.config + enabled max connections, just in case (it's still slow). 基于我在这里看到的其他问题,我在app.config +启用的最大连接中禁用了代理,以防万一(它仍然很慢)。 The section I added was: 我添加的部分是:

 <system.net>
<defaultProxy enabled="false">
  <proxy/>
  <bypasslist/>
  <module/>
</defaultProxy>
<connectionManagement>
  <add address="*" maxconnection="65000" />
</connectionManagement>

Here's a screenshot of what the code looks like and what is slow: 这是代码的样子和缓慢的截图:

替代文字

I'd appreciate any help... 4-8 seconds is way too long for a user to wait for an ajax request to complete. 我很感激任何帮助... 4-8秒对于用户等待ajax请求完成来说太长了。

Thanks! 谢谢!

The line 这条线

responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

does 3 things at once: 一次做三件事:

  1. It gets the response from the data. 它从数据中获得响应。
  2. It gets the response stream from the WebResponse object. 它从WebResponse对象获取响应流。
  3. It opens the stream. 它打开了流。

To improve timing analysis, and therefore understand where the bottleneck is, you first should recode the section to seperate the tasks. 为了改进时序分析,并因此了解瓶颈的位置,首先应该重新编写该部分以分离任务。

HttpWebResponse response = WebRequest.GetResponse();
Stream s = response.GetResponseStream();
reader = new StreamReader(s);

In the finally block you just have to close the reader, as this also closes the underlying stream. finally块中,您只需关闭阅读器,因为这也会关闭底层流。 Instead of explicitly closing the stream you could consider using an using block for the reader. 您可以考虑为阅读器using块,而不是显式关闭流。

using (Stream s = response.GetResponseStream()) {
    StreamReader reader = new StreamReader(s);
    responseData = reader.ReadToEnd();
}

I know that this is not a solution but maybe it provides a bit more insight as to where the time is lost. 我知道这不是一个解决方案,但它可能会提供更多的洞察时间丢失的时间。

A final suggestion, consider using asynchroneous execution to reduce the duration of the execution as perceived by the user. 最后的建议,考虑使用异步执行来减少用户所感知的执行持续时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM