WebClient查询需要很长时间才能完成,为什么?
问题描述:
这是我的C#代码。WebClient查询需要很长时间才能完成,为什么?
WebClient client = new WebClient();
while (true) {
html = client.DownloadString("http://google.com");
Console.WriteLine(string.Format("\tSize: {0}", html.Length));
}
大约需要9秒钟才能得到第一个结果。然后每个需要大约3秒钟。
当我用Java来完成时,它需要不到1秒的时间。
你为什么觉得C#这么慢?我该如何改进它?
答
您的网络可能有问题(如Mark评论)。
答
我注意到,第一个请求总是需要很长的时间使用WebClient或WebRequest ... 我做了一个与我构建的Socket-Http类相同的请求,它没有时间。
但是在第一次请求后,它应该更快,更好。
找到了解决的问题
尝试明确设置代理服务器。如果您没有定义代理,则HttpRequest类将花时间搜索一个代理。一旦它(或没有)找到它,它将在应用程序的整个生命周期中使用这些信息,加速后续的请求。
设置request.Proxy = null;
您的网络有问题。这在我的机器上需要0.16秒:System.Net.WebClient client = new System.Net.WebClient(); var sw = System.Diagnostics.Stopwatch.StartNew(); string html = client.DownloadString(“http://google.com”); Console.WriteLine(string.Format(“Size:{0}”,html.Length)); Console.WriteLine(“Elapsed:”+ sw.Elapsed); – Marek 2011-06-07 08:00:39
谷歌会扼杀你的请求。 – jgauffin 2011-06-07 08:01:26
@jgauffin:为什么? – Stefan 2011-06-07 08:02:34