2011-07-27 20 views
0

DownloadFiles()クラス内でFileDownloadを呼び出したいと思います。このメソッドはどこで呼び出すべきですか?以下のコードでは、bw_DoWorkを呼び出しましたが、コントロールがそこに到達していません。 Form Loadで宣言すると、worker.RunWorkerAsyncを使用しても、画面のレンダリングがフリーズします。バックグラウンドプロセスを使用してクラス内のメソッドを呼び出す

BackgroundWorker bw = new BackgroundWorker(); 
DownloadFile FileDownloadClass = new DownloadFile(); 

public MainWindow() 
{ 
    InitializeComponent(); 

    bw.WorkerReportsProgress = true; 
    bw.WorkerSupportsCancellation = true; 
    bw.DoWork += new DoWorkEventHandler(bw_DoWork); 
    bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); 
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); 
} 

private void bw_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 

    if ((worker.CancellationPending == true)) 
     e.Cancel = true; 
    else 
     worker.RunWorkerAsync(FileDownloadClass.DownloadFiles()); 
} 

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    if ((e.Cancelled == true)) 
    { 
     this.lblConnectionStatus.Content = " Download Canceled!"; 
    } 

    else if (!(e.Error == null)) 
    { 
     this.lblConnectionStatus.Content = ("Error: " + e.Error.Message); 
    } 

    else 
    { 
     this.lblConnectionStatus.Content = "Done!"; 
    } 
} 

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    lblConnectionStatus.Content = FileDownloadClass.StatusMessage; 
    progressBar1.Value = FileDownloadClass.TotalKbCompleted; 
} 

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
} 

編集

は、以下のようにbw_Workコードを変更:

private void bw_DoWork(object sender, DoWorkEventArgs e) 
    { 
     if ((bw.CancellationPending == true)) 
      e.Cancel = true; 
     else 
     { 
      FileDownloadClass.DownloadFiles(); 
      int PercentComplete = int.Parse((FileDownloadClass.TotalBytesReceived/FileDownloadClass.RemoteFileSize * 100).ToString()); 
      bw.ReportProgress(PercentComplete); 
     } 

をフォームのLoadイベントから、私は今、呼び出しています:

bw.RunWorkerAsync(); 

物事が開始されていますReportProgressイベントが進行状況バーを更新していない値。

編集:追加DownloadFileクラスコード

sealed class DownloadFile:INotifyPropertyChanged 
    { 

     #region Private Fields 
      // These fields hold the values for the public properties. 
      private int progressBarValue = 0; 
      private int totalKbCompleted = 0; 
      private int totalBytesReceived = 0; 
      private int remoteFileSize = 0; 

      private string fileName = String.Empty; 
      private string statusMessage = String.Empty; 
     #endregion 

      public event PropertyChangedEventHandler PropertyChanged; 

      private void NotifyPropertyChanged(String info) 
      { 
       if (PropertyChanged != null) 
       { 
        PropertyChanged(this, new PropertyChangedEventArgs(info)); 
       } 
      } 

      #region Public Properties 
      public int TotalKbCompleted 
      { 
       get { return this.totalKbCompleted; } 

       set 
       { 
        if (value != this.totalKbCompleted) 
        { 
         this.totalKbCompleted = value/1024; 
         NotifyPropertyChanged("TotalKbCompleted"); 
        } 
       }     
      } 

      public int TotalBytesReceived 
      { 
       get { return this.totalBytesReceived; } 

       set 
       { 
        if (value != this.totalBytesReceived) 
        { 
         this.totalBytesReceived = value; 
         NotifyPropertyChanged("TotalBytesReceived"); 
        } 
       } 
      } 

      public int RemoteFileSize 
      { 
       get { return this.remoteFileSize; } 

       set 
       { 
        if (value != this.remoteFileSize) 
        { 
         this.remoteFileSize = value; 
         NotifyPropertyChanged("RemoteFileSize"); 
        } 
       } 
      } 

      public string CurrentFileName 
      { 
       get { return this.fileName; } 

       set 
       { 
        if (value != this.fileName) 
        { 
         this.fileName = value; 
         NotifyPropertyChanged("CurrentFileName"); 
        } 
       } 
      } 

      public string StatusMessage 
      { 
       get { return this.statusMessage; } 

       set 
       { 
        if (value != this.statusMessage) 
        { 
         this.statusMessage = value; 
         NotifyPropertyChanged("StatusMessage"); 
        } 
       } 
      } 
      #endregion 

     public Int16 DownloadFiles() 
     { 
      try 
      { 

       statusMessage = "Attempting Connection with Server"; 

       DoEvents(); 
       // create a new ftpclient object with the host and port number to use 
       FtpClient ftp = new FtpClient("mySite", 21); 

       // registered an event hook for the transfer complete event so we get an update when the transfer is over 
       //ftp.TransferComplete += new EventHandler<TransferCompleteEventArgs>(ftp_TransferComplete); 

       // open a connection to the ftp server with a username and password 
       statusMessage = "Connected. Authenticating ...."; 
       ftp.Open("User Name", "Password"); 

       // Determine File Size of the compressed file to download 
       statusMessage = "Getting File Details"; 
       RemoteFileSize = Convert.ToInt32(ftp.GetFileSize("myFile.exe")); 

       ftp.TransferProgress += new EventHandler<TransferProgressEventArgs>(ftp_TransferProgress); 
       statusMessage = "Download from Server"; 
       ftp.GetFile("myFile.exe", "E:\\Test\\myFile.exe", FileAction.Create); 

       // close the ftp connection 
       ftp.Close(); 
       statusMessage = "Download Complete"; 
       return 1; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message.ToString()); 
       return 0; 
      } 

     } 


     private void ftp_TransferProgress(object sender, TransferProgressEventArgs e) 
     { 
      totalBytesReceived = Convert.ToInt32(e.BytesTransferred.ToString()); 
      totalKbCompleted = Convert.ToInt32(totalKbCompleted + Convert.ToInt32(totalBytesReceived)); 
      progressBarValue = totalKbCompleted; 
     } 
} 
+2

コードが奇妙に見えます。なぜあなたのバックグラウンドワーカーの中でバックグラウンドワーカーを始めますか? –

答えて

1

あなたの "BW" のワーカーを開始したことがありません。さらにDanielがコメントしたように、 "bw"ワーカーの中に別のBWを使用しています。これは無意味です。

MainWindow() とbw_DoWorkの中でFileDownloadClass.DownloadFiles()内で "bw"ワーカーを起動するだけです。

+0

オリジナルの投稿の編集済みコードを参照してください。 – RKh

+0

さて、あなたはあなたのダウンロードを行っているので、それが更新されていない、そして一度進捗状況を更新してください(すでに完了しているとき)、そしてあなたの仕事を完了したと宣言してください。ダウンロード方法自体の中から、そのダウンロードの途中で報告し、ダウンロードをしないで一度報告する必要があります。同じ理由でキャンセルはできません。 – chrisaut

+0

私は、DownloadFilesクラスにINotifyPropertyChangedインターフェイスを定義しました。そのクラスのプロパティを作成するには、フォームのプログレスバーの値を変更しますか? – RKh

0

スティーブンは言ったように、あなたはあなたのbwを始めることはありません。

FileDownloadClass.DownloadFiles()を開始するための単純なスレッドを試すことができます。

関連する問題