-3

我正在制作一个可以下载数万个文件的小软件。它现在根本没有效率,因为我一次下载每个文件,所以它很慢,而且很多文件小于 100ko。

你有什么提高下载速度的想法吗?

    /*******************************
        Worker work
    /********************************/
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        listCount = _downloadList.Count;
        // no GUI method !
        while (TotalDownloadFile < _downloadList.Count)
        {
            // handle closing form during download
            if (_worker.CancellationPending)
            {
                _mainView = null;
                _wc.CancelAsync();
                e.Cancel = true;
            }
            else if (!DownloadInProgress && TotalDownloadFile < listCount)
            {
                _lv = new launcherVersion(_downloadList[TotalDownloadFile]);
                var fileToDownloadPath = Info.getDownloadUrl() + _lv.Path;
                var saveFileToPath = Path.GetFullPath("./") + _lv.Path;
                if (Tools.IsFileExist(saveFileToPath))
                    File.Delete(saveFileToPath); // remove file if extist
                else
                    // create directory where the file will be created (use api this don't do anything on existing directory)
                    Directory.CreateDirectory(Path.GetDirectoryName(saveFileToPath));
                StartDownload(fileToDownloadPath, saveFileToPath);
                UpdateRemaingFile();
                _currentFile = TotalDownloadFile;
            }
        }
    }

开始下载功能

    /*******************************
        start the download of files
    /********************************/
    public void StartDownload(string fileToDownloadLink, string pathToSaveFile)
    {
        try
        {
            using (_wc = new WebClient())
            {
                _wc.DownloadProgressChanged += client_DownloadProgressChanged;
                _wc.DownloadFileCompleted += client_DownloadFileCompleted;
                _wc.DownloadFileAsync(new Uri(fileToDownloadLink), pathToSaveFile);
                DownloadInProgress = true;
            }
        }
        catch (WebException e)
        {
            MessageBox.Show(fileToDownloadLink);
            MessageBox.Show(e.ToString());
            _worker.CancelAsync();
            Application.Exit();
        }
    }
4

1 回答 1

0

扩展我的评论。您可能会使用多线程和并发来一次下载整个批次。您必须投入一些精力来确保每个线程成功完成并确保文件不会被下载两次。您必须使用lock之类的东西来保护您的集中列表。

我会亲自实现 3 个单独的列表:ReadyToDownloadDownloadInProgressDownloadComplete.

ReadyToDownload将包含所有需要下载的对象。DownloadInProgress将包含正在下载的项目和处理下载的任务。DownloadComplete将保存所有已下载的对象并引用执行下载的任务。

假设每个任务作为自定义对象的实例会更好地工作。该对象将接收对每个列表的引用,并且一旦工作完成或失败,它将处理更新列表。如果发生故障,您可以添加第四个列表来容纳失败的项目,或者将它们重新插入到ReadyToDownload列表中。

于 2017-09-15T13:23:08.567 回答