WebClient下载字符串(几个字符页面)太慢了
我正在尝试从URL下载字符串。 不幸的是,它很慢。
这是我的代码:
// One of these types for two bad solutions anyway // byte[] result = new byte[12]; // string result; using (var webClient = new System.Net.WebClient()) { String url = "http://bg2.cba.pl/realmIP.txt"; //result = webClient.DownloadString(url); // slow as hell //webClient.OpenRead(url).Read(result, 0, 12); // even slower }
这需要大约4-5秒,这对我来说似乎非常不合适……
该url的内容为IP
XX.YYY.ZZ.FF
固定,很抱歉我把这个问题放在这里,但是……这里是工作代码
string result; using (var webClient = new System.Net.WebClient()) { webClient.Proxy=null; String url = "http://bg2.cba.pl/realmIP.txt"; result = webClient.DownloadString(url); }
只需将Proxy设置为null
我尝试了你的代码并添加了一些输出。
using (var webClient = new System.Net.WebClient()) { Stopwatch timer = Stopwatch.StartNew(); String url = "http://bg2.cba.pl/realmIP.txt"; timer.Stop(); TimeSpan timespan = timer.Elapsed; String tex1 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10); timer = Stopwatch.StartNew(); String result = webClient.DownloadString(url); // slow as hell timespan = timer.Elapsed; String tex2 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10); timer = Stopwatch.StartNew(); Stream stream = webClient.OpenRead(url); timespan = timer.Elapsed; String tex3 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10); timer = Stopwatch.StartNew(); byte[] result2 = new byte[12]; int val = webClient.OpenRead(url).Read(result2, 0, 12); // even slower timespan = timer.Elapsed; String tex4 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10); textBox1.Text = result; t1.Text = tex1; t2.Text = tex2; t3.Text = tex3; t4.Text = tex4; }
使用以下结果
你的代码似乎没问题。 检查您的防火墙以及所涉及的所有内容
这显然是你的线/ pc /防火墙的问题
你可以在线测试:
大约需要500毫秒
在你自己的答案后更新
如果你想不使用代理,你应该使用msdn上所述的GetEmptyWebProxy() :
webClient.Proxy=GlobalProxySelection.GetEmptyWebProxy();