开发者

Calling a method in a class through background process

开发者 https://www.devze.com 2023-03-23 00:01 出处:网络
I want to call a method DownloadFiles() in a class FileDownload. Where should I call this method. In the below code, I have called in the bw_DoWork, but the control is not reaching there. If I declare

I want to call a method DownloadFiles() in a class FileDownload. Where should I call this method. In the below code, I have called in the bw_DoWork, but the control is not reaching there. If I declare in Form Load, then the screen rendering freezes even if I use 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)
{
}

Edited

Changed the bw_Work code as below:

   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);
        }

From the Form Load event, I am now calling:

bw.RunWorkerAsync();  

The things have started working fine except that the ReportProgress event is not updating the progress bar value.

Edited: Added DownloadFile Class Code

    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;
        }
}


You never start your "bw" worker. Furthermore, as Daniel commented, you are using another BW inside your "bw" worker. This is pointless.

Just start the "bw" worker inside your MainWindow() and inside bw_DoWork call FileDownloadClass.DownloadFiles().


As Steven said, you never start your bw.

Just for testing you can try to use a simple Thread for starting FileDownloadClass.DownloadFiles().

0

精彩评论

暂无评论...
验证码 换一张
取 消