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

本文关键字:方法 调用 后台进程 | 更新日期: 2023-09-27 18:03:45

我想在类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事件没有更新进度条值之外,事情已经开始正常工作了。

编辑:添加下载文件类代码

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

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

你从未启动过你的"bw" worker。此外,正如Daniel所评论的那样,您在"BW"worker中使用了另一个BW。这是没有意义的。

在MainWindow()中启动"bw" worker并在bw_DoWork内部调用FileDownloadClass.DownloadFiles()。

就像Steven说的,你从不开始你的工作。

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