【问题标题】:Why is the first request I do with a WebClient object always taking 15 seconds?为什么我对 WebClient 对象的第一个请求总是需要 15 秒?
【发布时间】:2010-11-06 21:14:17
【问题描述】:

我说的是 POST 请求,使用:

WebClient wc = new WebClient();
String result = wc.UploadString("http://example.com/", "data=hello, world!");

编辑:这是我现在的实际代码:

String result;
using (WebClient wc = new WebClient())
{
    result = wc.UploadString("http://" + "pastebin.com/api_public.php", "POST", "paste_code=" + LongDataEscape(Clipboard.GetText()));
}

如果您想了解 LongDataEscape:

    public String LongDataEscape(String Str)
    {
        String Output = "";
        int ByteCount = 32766;
        if (Str.Length > ByteCount)
        {
            for (int i = 0; i < Str.Length; i+= ByteCount)
            {
                if (Str.Length - i < ByteCount)
                    Output += Uri.EscapeDataString(Str.Substring(i, Str.Length - i));
                else
                    Output += Uri.EscapeDataString(Str.Substring(i, ByteCount));
            }
        }
        else
            Output = Uri.EscapeDataString(Str);
        return Output;
    }

我第一次执行上面的代码总是需要大约 15 秒(好吧也许是 10 秒),不管它是在哪个网站,但随后的相同代码片段只是瞬间完成。

我在想可能有一些设置可以做到这一点,但我还没有发现。

【问题讨论】:

  • 听起来像是在等待超时。您是否有可能尝试使用代理设置?我建议使用 Process Monitor (technet.microsoft.com/en-us/sysinternals/bb896645.aspx) 来查看 10-15 秒内发生了什么。
  • @Gabe 我没有这样做。我刚刚尝试了 procmon,但它在 10 秒的间隔内没有显示任何有趣的东西。只是没有做任何事情......

标签: c# .net performance webclient


【解决方案1】:

我修好了。

当您创建一个新的 WebClient 对象(FtpWebRequest 也是)时,您必须将其“代理”属性设置为空。例如:

WebClient wc = new WebClient();
wc.Proxy = null;

那么第一个请求将永远不会花费很长时间,并且您不会有任何问题。

【讨论】:

  • 很好,您找到了解决方案,但我建议您改为更改代理设置,这样您将忽略您的用户偏好,永远不会使用代理,即使他们指定了代理。
【解决方案2】:

第一次调用通常比后续调用花费更长的时间,但是 15 秒太多了。

尝试进行以下更改:

using(WebClient wc = new WebClient())
{
    String result = wc.UploadString("http://example.com/", "data=hello, world!");
}

【讨论】:

  • 是的,也许我在 15 秒内想太多了,但是没有办法可以减少这个初始调用时间?
  • @Angelo Geels,您尝试过我提出的更改吗?我怀疑 15 秒的延迟是由于您没有正确关闭 WebClient。
  • @Angelo Geels,你能用你正在运行的确切代码更新你的帖子吗?我的意思是你没有打电话给 example.com 对吗?
  • @Angel Geels,好:)。能不能用 fiddler 验证一下确实是 HTTP 请求需要很长时间。
  • @Angelo Geels,你可以从 www.fiddler2.com 获得 Fiddler
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多