简体   繁体   English

WebClient 查询需要很长时间才能完成,为什么?

[英]WebClient query takes too long to complete, why?

This is my C# code.这是我的 C# 代码。

WebClient client = new WebClient();

while (true) {
   html = client.DownloadString("http://google.com");
   Console.WriteLine(string.Format("\tSize: {0}", html.Length));
}

It takes around 9 seconds to get the first result.获得第一个结果大约需要 9 秒。 Then it takes around 3 seconds each.然后每个大约需要 3 秒。

When I do it with Java, it takes less than 1 second.当我使用 Java 执行此操作时,只需不到 1 秒。

Why do you think it's so slow with C#?为什么你认为 C# 这么慢? How can I improve it?我该如何改进它?

I noticed that the first Request always takes long using WebClient or WebRequest... I do the same request with a Socket-Http class I build and it takes no time.我注意到第一个请求使用 WebClient 或 WebRequest 总是需要很长时间......我使用我构建的 Socket-Http class 执行相同的请求,并且不需要时间。

But after the 1st request it should go faster, good.但是在第一次请求之后,它应该 go 更快,很好。

Found a fix for the problem找到解决问题的方法

Try explicitly setting the proxy.尝试显式设置代理。 If you don't have a proxy defined, the HttpRequest class will spend time searching for one.如果您没有定义代理,HttpRequest class 将花时间搜索一个。 Once it has (or hasn't) found one, it will use that information for the life of the application, speeding up subsequent requests.一旦找到(或未找到),它将在应用程序的整个生命周期中使用该信息,从而加快后续请求。

Set request.Proxy = null;设置request.Proxy = null;

You may have a problem with your network (as Mark comments).您的网络可能有问题(如 Mark 评论)。

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

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