C# 为什么同时下载的数量有限制?

C# 为什么同时下载的数量有限制?,c#,parallel-processing,download,C#,Parallel Processing,Download,我正在尝试制作我自己的简单网络爬虫。我想从URL下载具有特定扩展名的文件。我编写了以下代码: private void button1_Click(object sender, RoutedEventArgs e) { if (bw.IsBusy) return; bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(new string[] { URL.

我正在尝试制作我自己的简单网络爬虫。我想从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;
    }
…它不适用于更高的并行度,例如:

        new ParallelOptions { MaxDegreeOfParallelism = 5,  }
…我收到连接超时异常

起初我认为这是因为
WebClient

                //WebClient webClient = new WebClient();
                //webClient.DownloadFile(link, outPath);
…但是当我用使用
HttpWebRequest
的函数
DownloadFile
替换它时,我仍然得到了错误

我已经在很多网页上测试过了,没有任何变化。我还通过chrome的扩展名“下载主机”确认,这些web服务器允许多个并行下载。
有人知道为什么我在尝试并行下载多个文件时会出现超时异常吗?

您需要分配超时。到同一主机的默认并发连接为2。另请参见关于使用web.config。

据我所知,IIS将限制传入和传出的连接总数,但此数目应在10^3而不是~5的范围内

您是否可能正在测试相同的url?我知道很多web服务器限制来自客户端的同时连接数。你是通过下载10份来测试的吗

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


只是好奇:为什么在工作完成时抛出异常?我最后抛出的异常是一段临时代码。当一切都完成时,我需要一些东西快速查看,所以我想“为什么不呢?”。非常感谢!我刚通过设置ServicePointManager.DefaultConnectionLimit使它工作起来!你为我节省了很多时间,也为我工作过!谢谢
                //WebClient webClient = new WebClient();
                //webClient.DownloadFile(link, outPath);