Web客户端是很慢 [英] WebClient is very slow

查看:166
本文介绍了Web客户端是很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题的Web客户端。

I have problem with Webclient.

有非常慢。大约需要3-5秒,从一个网站downloadString。 我没有任何网络问题。

It is very slow. It takes about 3-5 seconds to downloadString from one website. I don't have any network problems.

这是我的改性的Web客户端。

This is my Modifed WebClient.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace StatusChecker
{
    class WebClientEx: WebClient
    {
        public CookieContainer CookieContainer { get; private set; }

        public WebClientEx()
        {
            CookieContainer = new CookieContainer();

            ServicePointManager.Expect100Continue = false;
            Encoding = System.Text.Encoding.UTF8;

            WebRequest.DefaultWebProxy = null;
            Proxy = null;
        }

        public void ClearCookies()
        {
            CookieContainer = new CookieContainer();
        }

        protected override WebRequest GetWebRequest(Uri address)
        {

            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = CookieContainer;
            }
            return request;
        }
    }
}

更新: 在Wireshark中我看到一个DownladString发送和接收几千个数据包。

UPDATE: In wireshark I saw that single DownladString is sending and receiving few thousands packets.

推荐答案

可能有两个问题在这里手(即我也注意到在我自己的程序previously):

There may be two issues at hand here (that I've also noticed in my own programs previously):

  • 的第一个请求需要一个异常长的时间:这是因为的WebRequest 默认情况下检测并加载代理服务器设置在第一次启动时,它可能需要相当长一段时间。要停止这一点,只需设置代理属性( WebRequest.Proxy ),以,它会绕过检查(只要你能直接访问互联网)
  • 您不能一次下载超过2项:在默认情况下,你只能有2个并发的HTTP连接打开。要改变这种情况,设置 ServicePointManager.DefaultConnectionLimit 更大的东西。我通常设置为 int.MaxValue (只是确保你没有垃圾邮件1,000,000个连接主机)。
  • The first request takes an abnormally long time: This occurs because WebRequest by default detects and loads proxy settings the first time it starts, which can take quite a while. To stop this, simply set the proxy property (WebRequest.Proxy) to null and it'll bypass the check (provided you can directly access the internet)
  • You can't download more than 2 items at once: By default, you can only have 2 simultaneous HTTP connections open. To change this, set ServicePointManager.DefaultConnectionLimit to something larger. I usually set this to int.MaxValue (just make sure you don't spam the host with 1,000,000 connections).

这篇关于Web客户端是很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆