4

我正在尝试从 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
4

3 回答 3

11

已修复,我猜很抱歉把这个问题放在这里,但是......这是工作代码

string result;
using (var webClient = new System.Net.WebClient())
{
    webClient.Proxy=null;
    String url = "http://bg2.cba.pl/realmIP.txt";
    result = webClient.DownloadString(url);
}

只需将代理设置为空

于 2014-12-22T13:37:50.163 回答
3

这显然是你线路/PC/防火墙的问题

您可以在线测试它:

http://goo.gl/XRqLjn

大约需要 500 毫秒

在此处输入图像描述

自己回答后更新

如果您不想使用任何代理,您应该使用GetEmptyWebProxy(),如msdn中所述:

webClient.Proxy=GlobalProxySelection.GetEmptyWebProxy();
于 2014-12-22T13:41:25.020 回答
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;
        }

结果如下

在此处输入图像描述

你的代码似乎没问题。检查你的防火墙和所有涉及的东西

于 2014-12-22T13:37:33.983 回答