【问题标题】:Why is there a limit in the concurrent number of downloads?为什么有并发下载次数限制?
【发布时间】:2012-06-13 15:11:22
【问题描述】:

我正在尝试制作自己的简单网络爬虫。我想从 URL 下载具有特定扩展名的文件。我写了以下代码:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (bw.IsBusy) return;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerAsync(new string[] { URL.Text, SavePath.Text, Filter.Text });
    }
    //--------------------------------------------------------------------------------------------
    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            ThreadPool.SetMaxThreads(4, 4);
            string[] strs = e.Argument as string[];
            Regex reg = new Regex("<a(\\s*[^>]*?){0,1}\\s*href\\s*\\=\\s*\\\"([^>]*?)\\\"\\s*[^>]*>(.*?)</a>", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            int i = 0;
            string domainS = strs[0];
            string Extensions = strs[2];
            string OutDir = strs[1];
            var domain = new Uri(domainS);
            string[] Filters = Extensions.Split(new char[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string outPath = System.IO.Path.Combine(OutDir, string.Format("File_{0}.html", i));

            WebClient webClient = new WebClient();
            string str = webClient.DownloadString(domainS);
            str = str.Replace("\r\n", " ").Replace('\n', ' ');
            MatchCollection mc = reg.Matches(str);
            int NumOfThreads = mc.Count;

            Parallel.ForEach(mc.Cast<Match>(), new ParallelOptions { MaxDegreeOfParallelism = 2,  },
            mat =>
            {
                string val = mat.Groups[2].Value;
                var link = new Uri(domain, val);
                foreach (string ext in Filters)
                    if (val.EndsWith("." + ext))
                    {
                        Download((object)new object[] { OutDir, link });
                        break;
                    }
            });
            throw new Exception("Finished !");

        }
        catch (System.Exception ex)
        {
            ReportException(ex);
        }
        finally
        {

        }
    }
    //--------------------------------------------------------------------------------------------
    private static void Download(object o)
    {
        try
        {
            object[] objs = o as object[];
            Uri link = (Uri)objs[1];
            string outPath = System.IO.Path.Combine((string)objs[0], System.IO.Path.GetFileName(link.ToString()));
            if (!File.Exists(outPath))
            {
                //WebClient webClient = new WebClient();
                //webClient.DownloadFile(link, outPath);

                DownloadFile(link.ToString(), outPath);
            }
        }
        catch (System.Exception ex)
        {
            ReportException(ex);
        }
    }
    //--------------------------------------------------------------------------------------------
    private static bool DownloadFile(string url, string filePath)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.UserAgent = "Web Crawler";
            request.Timeout = 40000;
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
            {
                const int siz = 1000;
                byte[] bytes = new byte[siz];
                for (; ; )
                {
                    int count = stream.Read(bytes, 0, siz);
                    fs.Write(bytes, 0, count);
                    if (count == 0) break;
                }
                fs.Flush();
                fs.Close();
            }
        }
        catch (System.Exception ex)
        {
            ReportException(ex);
            return false;
        }
        finally
        {

        }
        return true;
    }

问题在于,虽然它适用于 2 次并行下载:

        new ParallelOptions { MaxDegreeOfParallelism = 2,  }

...它不适用于更高程度的并行性,例如:

        new ParallelOptions { MaxDegreeOfParallelism = 5,  }

...我得到连接超时异常。

一开始我以为是因为WebClient

                //WebClient webClient = new WebClient();
                //webClient.DownloadFile(link, outPath);

...但是当我将它替换为使用 HttpWebRequest 的函数 DownloadFile 时,我仍然收到错误。

我在许多网页上测试过它,但没有任何改变。我还通过 chrome 的扩展程序“Download Master”确认这些 Web 服务器允许多个并行下载。 有人知道为什么我在尝试并行下载许多文件时会出现超时异常吗?

【问题讨论】:

  • 只是好奇:为什么工作完成后会抛出异常?
  • 我最后抛出的异常是一段临时代码。我需要快速查看什么时候完成,所以我想“为什么不呢?”。

标签: c# parallel-processing download


【解决方案1】:

您需要分配ServicePointManager.DefaultConnectionLimit。到同一主机的默认并发连接数为 2。另请参阅 related SO post 使用 web.config connectionManagement

【讨论】:

  • 非常感谢!我刚刚通过设置 ServicePointManager.DefaultConnectionLimit 让它工作!你为我节省了很多时间。
  • 也为我工作!谢谢!
【解决方案2】:

据我所知,IIS 会限制进出连接的总数,但是这个数字应该在 10^3 而不是 ~5 的范围内。

您是否有可能使用相同的网址进行测试?我知道很多 Web 服务器会限制来自客户端的同时连接数。例如:您是否尝试下载 10 份 http://www.google.com 进行测试?

如果是这样,您可能想尝试使用不同网站的列表进行测试,例如:

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多