如何显示并行下载的各个ProgressBar?

时间:2016-05-18 10:34:23

标签: .net

我正在使用WebClient并同时下载4个文件。文件是并行下载的,我可以在文件夹中看到文件大小的变化。现在我想显示每个文件的进度条。这是我到目前为止所尝试的,但进展并未发生。有人可以帮忙吗

 private void Button_Click(object sender, RoutedEventArgs e)
    {
            System.Net.ServicePointManager.DefaultConnectionLimit = 10;
            List<String> files = new List<String>();
            String localPath = "";
            files.Add(file1);
            files.Add(file2);
            files.Add(file3);
            files.Add(file4);

            foreach (String fi in files)
            {
                localPath = "C:\\Download\\" + fi.Split('/')[5].ToString();
                WebClient client = new WebClient();

                client.DownloadProgressChanged += (sender1, e1) => client_DownloadProgressChanged(sender1, e1, z);

                client.DownloadFileAsync(new Uri(fi), localPath, count);
                count += 1;
            }
     }

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e, int RowNumber)
        {
            ProgressBar[] pb = new ProgressBar[4];

            pb[RowNumber-1] = new ProgressBar();
            pb[RowNumber-1].Width = 400;
            pb[RowNumber-1].Height =20;
            pnl.Children.Add(pb[RowNumber-1]);
            pb[RowNumber-1].Value = e.ProgressPercentage;
        }

1 个答案:

答案 0 :(得分:0)

这里有多个选项。最好的解决方案是

  1. DownloadProgressChangedEventHandler方法中为每个文件名使用其他参数。 了解如何执行此操作here
  2. 使用不同的DownloadProgressChangedEventHandler
  3. 许多其他选项,即Parallel.ForEach
  4. 第一个解决方案代码(未经过测试 - 我现在无法访问IDE)

    List<String> files = new List<String>();
    List<ProgressBar> pbs = new List<ProgressBar>();
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        System.Net.ServicePointManager.DefaultConnectionLimit = 10; 
        String localPath = "";
        files.Add(file1);
        files.Add(file2);
        files.Add(file3);
        files.Add(file4);   
    
        foreach (String fi in files)
        {
            ProgressBar pb = new ProgressBar();
            pb.Width = 400;
            pb.Height =20;
            pnl.Children.Add(pb);
            pbs.add(pb);
    
            localPath = "C:\\Download\\" + fi.Split('/')[5].ToString();
            WebClient client = new WebClient();
    
            client.DownloadProgressChanged += (sender1, e1) => client_DownloadProgressChanged(sender1, e1, fi);
    
            client.DownloadFileAsync(new Uri(fi), localPath, count);
            count += 1;
        }
    }
    
    
    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e, string fi)
    {       
        int pbNumber = files.IndexOf(fi);           
        pbs[pbNumber].Value = e.ProgressPercentage;
    }