【问题标题】:Downloading multiple files synchronously C#同步下载多个文件C#
【发布时间】:2015-12-12 12:36:20
【问题描述】:

我正在尝试使用多个线程下载多个文件。该程序使用 BFS 算法来访问给定特定 url 的所有文件:http://www.police.am/Hanraqve/ 问题是当多个线程被释放时,可以多次下载同一个文件。我正在考虑一种同步下载过程的方法,以便每个文件仅在互斥锁或信号量的帮助下下载一次。任何想法或实际代码将不胜感激。这是我的初始代码

    public static async Task Download()
    {
        nodes.Enqueue(root);
        while (nodes.Count() != 0)
        {
            String currentNode = "";
            if (nodes.TryDequeue(out currentNode))
            {
                if (!visitedNodes.Contains(currentNode))
                {
                    visitedNodes.Add(currentNode);
                    if (isFolder(currentNode))
                    {
                        List<String> urls = GetUrlsFromHtml(currentNode);
                        foreach (String url in urls)
                        {
                            nodes.Enqueue(url);
                        }
                    }
                    else
                    {
                        string fileName = currentNode.Remove(0, currentNode.LastIndexOf('/') + 1);

                        using (WebClient webClient = new WebClient())
                        {
                            await webClient.DownloadFileTaskAsync(new Uri(currentNode), destinationFolderPath + @"\" + fileName);
                            files.Enqueue(destinationFolderPath + @"\" + fileName);
                        }
                    }
                }

            }
        }


        //cts.Cancel();
    }

    public static List<String> GetUrlsFromHtml(string url)
    {
        HtmlWeb hw = new HtmlWeb();
        HtmlDocument doc = hw.Load(url);
        List<String> urls = new List<String>();
        foreach (HtmlNode htmlNode in doc.DocumentNode.SelectNodes("//a[@href]"))
        {
            string hrefValue = htmlNode.Attributes["href"].Value;
            if (hrefValue[0] >= '1' && hrefValue[0] <= '9')
            {
                urls.Add(url + hrefValue);
            }
        }
        return urls;
    }

    public static bool isFolder(string url)
    {
        return url.EndsWith("/");
    }
}

}

【问题讨论】:

  • 为什么会被多次下载?同一个文件可以出现在多个网址中吗?
  • 例如,一个线程可以传递 if (!visitedNodes.Contains(currentNode)) 行,而另一个线程将节点添加到访问节点列表中,它们都将下载相同的文件
  • 然后使用线程安全的集合。我也许会改变算法。遍历图中的每个节点并找到所有可能的文件。然后,并且只有在那时,才执行并发下载。

标签: c# multithreading download synchronization


【解决方案1】:

检查您存储的访问过的网址,它们可能不同但仍会转到同一页面。

http://foo.com?a=bar http://foo.bar?b=foo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多