代码之家  ›  专栏  ›  技术社区  ›  mpen

WebException不应该发生在哪里?

  •  0
  • mpen  · 技术社区  · 15 年前

    var task = Task.Factory.StartNew(() =>
    {
        while (!bc.IsCompleted && !cts.Token.IsCancellationRequested)
        {
            PriorityDownloadPair pd;
            if (bc.TryTake(out pd))
            {
                var baseUri = pd.Value.Uri;
                Console.WriteLine("({0}) {1}", pd.Key, baseUri.AbsoluteUri);
                IEnumerable<HtmlNode> sq = null;
                try
                {
                    sq = SharpQuery.SharpQuery.Load(baseUri);
                }
                catch (WebException we)
                {
                    Console.WriteLine(we.Message);
                    continue;
                }
                foreach (var node in sq.Find("a[href]"))
                {
                    bc.Add(new PriorityDownloadPair(1, new DownloadItem { Uri = new Uri(baseUri, node.Attributes["href"].Value) }));
                }
            }
        }
    }, cts.Token);
    

    它可以正常运行一段时间(跟踪并下载找到的每个链接),直到找到404。

    public static IEnumerable<HtmlNode> Load(Uri uri)
    {
        var doc = new HtmlDocument();
        WebClient wc = new WebClient();
        using (var str = wc.OpenRead(uri))
            doc.Load(str);
        yield return doc.DocumentNode;
    }
    

    如果我在调用堆栈上,它会指向这一行:

    foreach (var node in sq.Find("a[href]"))
    

    sq.Find 甚至不接触任何网络界面。发生什么事?

    这些线是同步的,

            using (var str = wc.OpenRead(uri))
                doc.Load(str);
    

    1 回复  |  直到 15 年前
        1
  •  1
  •   Shiraz Bhaiji    15 年前

    这是因为在实际读取try块之后的数据之前,不会执行加载。

    推荐文章