且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何使用异步Web客户端下载多个文件,但一次?

更新时间:2023-10-02 09:42:04

我所做的是填充包含我的所有URL队列,然后我下载队列中的每个项目。当有没有留下任何物品,然后我就可以处理所有的项目。我嘲笑一些code以下了。请记住,在code以下是下载字符串和而不是文件。它不应该是太难修改低于code。

 专用队列<串GT; _items =新队列<串GT;();
    私人列表<串GT; _results =新的List<串GT;();    私人无效PopulateItemsQueue()
    {
        _items.Enqueue(some_url_here);
        _items.Enqueue(perhaps_another_here);
        _items.Enqueue(and_a_third_item_as_well);        DownloadItem();
    }    私人无效DownloadItem()
    {
        如果(_items.Any())
        {
            变种nextItem = _items.Dequeue();            VAR的WebClient =新的WebClient();
            webClient.DownloadStringCompleted + = OnGetDownloadedStringCompleted;
            webClient.DownloadStringAsync(新的URI(nextItem));
            返回;
        }        ProcessResults(_results);
    }    OnGetDownloadedStringCompleted私人无效(对象发件人,DownloadStringCompletedEventArgs E)
    {
        如果(e.Error == NULL和放大器;&安培;!string.IsNullOrEmpty(e.Result))
        {
            //做e.Result字符串的东西。
            _results.Add(e.Result);
        }
        DownloadItem();
    }

编辑:
我已经修改了code使用的队列。不完全知道你怎么想的进展工作。我敢肯定,如果你想以满足所有下载的进度,那么你可以存储项目数在PopulateItemsQueue()方法,并使用在进度改变方法领域。

 专用队列<串GT; _downloadUrls =新队列<串GT;();    私人无效downloadFile(IEnumerable的<串GT;的URL)
    {
        的foreach(URL中VAR URL)
        {
            _downloadUrls.Enqueue(URL);
        }        //开始下载
        btnGetDownload.Text =正在下载...;
        btnGetDownload.Enabled = FALSE;
        progressBar1.Visible =真;
        lblFileName.Visible = TRUE;        下载文件();
    }    私人无效DownloadFile()
    {
        如果(_downloadUrls.Any())
        {
            Web客户端的客户端=新的WebClient();
            client.DownloadProgressChanged + = client_DownloadProgressChanged;
            client.DownloadFileCompleted + = client_DownloadFileCompleted;            VAR URL = _downloadUrls.Dequeue();
            字符串文件名= url.Substring(url.LastIndexOf(/)+ 1,
                        (url.Length - url.LastIndexOf(/) - 1));            client.DownloadFileAsync(新的URI(URL),C:\\\\ \\\\ TEST4+文件名);
            lblFileName.Text =网址;
            返回;
        }        //下载结束
        btnGetDownload.Text =下载完成;
    }    私人无效client_DownloadFileCompleted(对象发件人,AsyncCompletedEventArgs E)
    {
        如果(e.Error!= NULL)
        {
            //处理错误场景
            扔e.Error;
        }
        如果(e.Cancelled)
        {
            //手柄取消场景
        }
        下载文件();
    }    无效client_DownloadProgressChanged(对象发件人,DownloadProgressChangedEventArgs E)
    {
        双bytesIn = double.Parse(e.BytesReceived.ToString());
        双totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        双率= bytesIn / totalBytes * 100;
        progressBar1.Value = int.Parse(Math.Truncate(百分比)的ToString());
    }

It has been surprisingly hard to find a code example of downloading multiple files using the webclient class asynchronous method, but downloading one at a time.

How can I initiate a async download, but wait until the first is finished until the second, etc. Basically a que.

(note I do not want to use the sync method, because of the increased functionality of the async method.)

The below code starts all my downloads at once. (the progress bar is all over the place)

private void downloadFile(string url)
        {
            WebClient client = new WebClient();

            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

            // Starts the download
            btnGetDownload.Text = "Downloading...";
            btnGetDownload.Enabled = false;
            progressBar1.Visible = true;
            lblFileName.Text = url;
            lblFileName.Visible = true;
            string FileName = url.Substring(url.LastIndexOf("/") + 1,
                            (url.Length - url.LastIndexOf("/") - 1));
             client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);

        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {

        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
        }

What I have done is populate a Queue containing all my urls, then I download each item in the queue. When there are no items left, I can then process all the items. I've mocked some code up below. Keep in mind, the code below is for downloading strings and not files. It shouldn't be too difficult to modify the below code.

    private Queue<string> _items = new Queue<string>();
    private List<string> _results = new List<string>();

    private void PopulateItemsQueue()
    {
        _items.Enqueue("some_url_here");
        _items.Enqueue("perhaps_another_here");
        _items.Enqueue("and_a_third_item_as_well");

        DownloadItem();
    }

    private void DownloadItem()
    {
        if (_items.Any())
        {
            var nextItem = _items.Dequeue();

            var webClient = new WebClient();
            webClient.DownloadStringCompleted += OnGetDownloadedStringCompleted;
            webClient.DownloadStringAsync(new Uri(nextItem));
            return;
        }

        ProcessResults(_results);
    }

    private void OnGetDownloadedStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null && !string.IsNullOrEmpty(e.Result))
        {
            // do something with e.Result string.
            _results.Add(e.Result);
        }
        DownloadItem();
    }

Edit: I've modified your code to use a Queue. Not entirely sure how you wanted progress to work. I'm sure if you wanted the progress to cater for all downloads, then you could store the item count in the 'PopulateItemsQueue()' method and use that field in the progress changed method.

    private Queue<string> _downloadUrls = new Queue<string>();

    private void downloadFile(IEnumerable<string> urls)
    {
        foreach (var url in urls)
        {
            _downloadUrls.Enqueue(url);
        }

        // Starts the download
        btnGetDownload.Text = "Downloading...";
        btnGetDownload.Enabled = false;
        progressBar1.Visible = true;
        lblFileName.Visible = true;

        DownloadFile();
    }

    private void DownloadFile()
    {
        if (_downloadUrls.Any())
        {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadFileCompleted += client_DownloadFileCompleted;

            var url = _downloadUrls.Dequeue();
            string FileName = url.Substring(url.LastIndexOf("/") + 1,
                        (url.Length - url.LastIndexOf("/") - 1));

            client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);
            lblFileName.Text = url;
            return;
        }

        // End of the download
        btnGetDownload.Text = "Download Complete";
    }

    private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            // handle error scenario
            throw e.Error;
        }
        if (e.Cancelled)
        {
            // handle cancelled scenario
        }
        DownloadFile();
    }

    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    }