C#Parallel WebClient - 操作已超时

时间:2013-10-03 18:46:40

标签: c# .net webclient parallel.foreach webclient-download

我是新手,想知道为什么我在webclient downloadstring()parallel遇到错误。我不知道是不是因为我的连接速度缓慢。这是我的代码:

for (int i = 2; i <= 5; i++)
        {
            string ebayLink = "http://www.ebay.de/sch/Studium-Wissen-/1105/i.html?LH_Auction=1&_sop=1&_nkw=&_pgn=" + i;
            //string ebayLink = "http://www.ebay.de/sch/Schule-Ausbildung-/40434/i.html?LH_Auction=1&_sop=1&_nkw=&_pgn=" + i;
            ebayLink = "http://www.ebay.de/sch/i.html?LH_Auction=1&_sacat=0&_from=R40&_nkw=B%C3%BCcher&_sop=1&_pgn=" + i; 

            HtmlWeb hw = new HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = hw.Load(ebayLink);


            List<string> eanList = new List<string>();

            List<string> links = new List<string>();

            foreach (var link in doc.DocumentNode.SelectNodes("//a[@href]"))
            {
                string url = link.GetAttributeValue("href", "");
                if (url.Contains(".de/itm") && !links.Contains(url) && !url.Contains("pt=Zeitschriften") && !url.Contains("pt=Belletristik"))
                {
                    links.Add(url);
                }
            }

            Parallel.ForEach(links, link =>
            {
                WebClient wc = new WebClient();
                string html = wc.DownloadString(link);

                EbayItem ebayItem = new EbayItem(html);

                string ean = ebayItem.ean;


                string amazonUsedPrice = string.Empty;

                amazonUsedPrice = getAmazonUsedPrice(ean);

                Product product = new Product();
                product.EbayUrl = link;
                product.Ean = ean;
                product.AmazonPriceString = amazonUsedPrice;
                product.ebayItem = ebayItem;
                productList.Add(product);


            } 
     );}

string html = wc.DownloadString(link);发生错误。我在输出上看到它在到达至少20个链接时停止。

1 个答案:

答案 0 :(得分:1)

您的连接正在等待先前的连接关闭,因此超时。与同一主机的并发连接的默认限制为2.尝试在输入Parallel电话前增加该限制:

System.Net.ServicePointManager.DefaultConnectionLimit = int.MaxValue;

详细了解DefaultConnectionLimit here

  

物业价值

     

输入:System.Int32

     

ServicePoint对象允许的最大并发连接数。默认值为2.