2012-01-25 22 views
1
    foreach (string line in textBox3.Lines) 
        { 
         int pos = line.IndexOf("?v="); 
         string videoid = line.Substring(pos + 3, 11); 
         GetFile(videoid); 
        } 

     GetFile() { 
     ...code 

     WebClient webClient = new WebClient(); 
     webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
     webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); 
     webClient.DownloadFileAsync(new Uri(fileRequest), @textBox2.Text + @"\" + title + ".mp3"); 
    } 

    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     progressBar1.Value = e.ProgressPercentage; 
    } 

問題是如何hadle一個進度條和許多webclients?這種情況是行不通的,因爲每個客戶都在更新自己的酒吧,這很瘋狂,那麼正確的方法是什麼? PS。我不能只使用一個WebClient,我在爲每個文件提出請求之前。一個進度條與許多webclients

+0

如果你有2個Web客戶端,一個是50%了,而另一個40%完成後,你想讓它顯示45%?例如他們的平均數? –

+0

是的,類似的東西。但每個客戶都在發送自己的地位,他們的電話號碼是未知的<這不是問題>,但仍然不知道如何表示價值,不知道如何總結所有x進展。 – mishe

+0

@mishe更新了我的答案,以確保getter不會被零除。這可能很重要:p –

回答

1

我想像你可以做這樣的事情:

public class WebClientProgressManager : INotifyPropertyChanged 
     { 
      private readonly Dictionary<WebClient,int> _clients = new Dictionary<WebClient, int>(); 
      private const string TotalProgressPropertyName = "TotalProgress"; 
      public void Add(WebClient client) 
      { 
       if (client == null) 
        throw new ArgumentNullException("client"); 
       if (_clients.ContainsKey(client)) return; 

       client.DownloadProgressChanged += (s, e) => 
                 { 
                  if (e.ProgressPercentage == 100) 
                  { 
                   _clients.Remove((WebClient)s); 
                  } 
                  RaisePropertyChanged(TotalProgressPropertyName); 
                 }; 
       _clients.Add(client,0); 

      } 

      private void RaisePropertyChanged(string propertyName) 
      { 
       if (PropertyChanged != null) 
       { 
        PropertyChanged.Invoke(this,new PropertyChangedEventArgs(propertyName)); 
       } 
      } 

      public int TotalProgress 
      { 

       get 
       { 
        if (_clients.Count == 0) return 100; //need something here to prevent divide-by-zero 
        int progress = _clients.Sum(client => client.Value); 
        return progress/_clients.Count; 
       } 
      } 

      #region Implementation of INotifyPropertyChanged 

      public event PropertyChangedEventHandler PropertyChanged; 

      #endregion 
     }