通过后台进程调用类中的方法

时间:2011-07-27 09:46:03

标签: c# .net .net-4.0

我想在课程 FileDownload 中调用 DownloadFiles()方法。我应该在哪里调用此方法。在下面的代码中,我调用了 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);
        }

从Form 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 个答案:

答案 0 :(得分:1)

你永远不会开始你的“bw”工作者。此外,正如Daniel评论的那样,你在“bw”工作者中使用了另一个BW。这毫无意义。

在MainWindow中启动“bw”工作人员()  在bw_DoWork里面调用FileDownloadClass.DownloadFiles()。

答案 1 :(得分:0)

史蒂文说,你永远不会开始你的bw。

只是为了测试,你可以尝试使用一个简单的线程来启动FileDownloadClass.DownloadFiles()。