WebClient下载字符串(几个字符页面)太慢了

时间:2014-12-22 13:10:48

标签: c# performance webclient downloadstring

我正在尝试从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秒,这对我来说似乎非常不合适......

此网址的内容为IP

 XX.YYY.ZZ.FF

3 个答案:

答案 0 :(得分:6)

已修复,很抱歉我想在这里提出这个问题,但是......这里是工作代码

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

答案 1 :(得分:2)

我尝试了你的代码并添加了一些输出。

        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;
        }

使用以下结果

enter image description here

您的代码似乎没问题。 检查您的防火墙以及所涉及的所有内容

答案 2 :(得分:2)

这显然是你行/ pc /防火墙的问题

您可以在线测试:

http://goo.gl/XRqLjn

大约需要500毫秒

enter image description here

在您自己的回答后更新

如果您不想使用代理,则应使用GetEmptyWebProxy()中所述的msdn

webClient.Proxy=GlobalProxySelection.GetEmptyWebProxy();