通过调用后台进程在一个类中的方法 [英] Calling a method in a class through background process

查看:171
本文介绍了通过调用后台进程在一个类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个类中的 FileDownload 调用一个方法 DownloadFiles()。我应该在哪里调用此方法。在下面的code,我呼吁在 bw_DoWork ,但控制没有达到那里。如果我宣布在窗体加载,然后屏幕呈现冻结,即使我使用 worker.RunWorkerAsync

  BackgroundWorker的体重=新的BackgroundWorker();
DownloadFile FileDownloadClass =新DownloadFile();

公共主窗口()
{
    的InitializeComponent();

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

私人无效bw_DoWork(对象发件人,DoWorkEventArgs E)
{
    BackgroundWorker的工人=发件人为BackgroundWorker的;

    如果((worker.CancellationPending ==真))
        e.Cancel =真;
    其他
        worker.RunWorkerAsync(FileDownloadClass.DownloadFiles());
}

私人无效bw_RunWorkerCompleted(对象发件人,RunWorkerCompletedEventArgs E)
{
    如果((e.Cancelled ==真))
    {
        this.lblConnectionStatus.Content =下载已取消!;
    }

    否则,如果(!(e.Error == NULL))
    {
        this.lblConnectionStatus.Content =(错误:+ e.Error.Message);
    }

    其他
    {
        this.lblConnectionStatus.Content =完成!;
    }
}

私人无效bw_ProgressChanged(对象发件人,ProgressChangedEventArgs E)
{
    lblConnectionStatus.Content = FileDownloadClass.StatusMessage;
    progressBar1.Value = FileDownloadClass.TotalKbCompleted;
}

私人无效Window_Loaded(对象发件人,RoutedEventArgs E)
{
}
 

编辑

改变了bw_Work code如下:

 私人无效bw_DoWork(对象发件人,DoWorkEventArgs E)
    {
        如果((bw.CancellationPending ==真))
            e.Cancel =真;
        其他
        {
            FileDownloadClass.DownloadFiles();
            INT PercentComplete = int.Parse((FileDownloadClass.TotalBytesReceived / FileDownloadClass.RemoteFileSize * 100)的ToString());
            bw.ReportProgress(PercentComplete);
        }
 

在窗体的Load事件,我现在打电话:

  bw.RunWorkerAsync();
 

的事情已经开始工作正常,只是ReportProgress事件没有更新进度条值。

编辑:新增DownloadFile类code

 密封类DownloadFile:INotifyPropertyChanged的
    {

        #地区的私人领域
            //这些字段保存的公共属性的值。
            私人诠释progressBarValue = 0;
            私人诠释totalKbCompleted = 0;
            私人诠释totalBytesReceived = 0;
            私人诠释remoteFileSize = 0;

            私人字符串文件名=的String.Empty;
            私人字符串statusMessage =的String.Empty;
        #endregion

            公共事件PropertyChangedEventHandler的PropertyChanged;

            私人无效NotifyPropertyChanged(字符串信息)
            {
                如果(的PropertyChanged!= NULL)
                {
                    的PropertyChanged(这一点,新PropertyChangedEventArgs(信息));
                }
            }

            #地区的公共属性
            公众诠释TotalKbCompleted
            {
                {返回this.totalKbCompleted; }

                组
                {
                    如果(值!= this.totalKbCompleted)
                    {
                        this.totalKbCompleted =值/ 1024;
                        NotifyPropertyChanged(TotalKbCompleted);
                    }
                }
            }

            公众诠释TotalBytesReceived
            {
                {返回this.totalBytesReceived; }

                组
                {
                    如果(值!= this.totalBytesReceived)
                    {
                        this.totalBytesReceived =价值;
                        NotifyPropertyChanged(TotalBytesReceived);
                    }
                }
            }

            公众诠释RemoteFileSize
            {
                {返回this.remoteFileSize; }

                组
                {
                    如果(值!= this.remoteFileSize)
                    {
                        this.remoteFileSize =价值;
                        NotifyPropertyChanged(RemoteFileSize);
                    }
                }
            }

            公共字符串CurrentFileName
            {
                {返回this.fileName; }

                组
                {
                    如果(值!= this.fileName)
                    {
                        this.fileName =价值;
                        NotifyPropertyChanged(CurrentFileName);
                    }
                }
            }

            公共字符串StatusMessage
            {
                {返回this.statusMessage; }

                组
                {
                    如果(值!= this.statusMessage)
                    {
                        this.statusMessage =价值;
                        NotifyPropertyChanged(StatusMessage);
                    }
                }
            }
            #endregion

        公共Int16的DownloadFiles()
        {
            尝试
            {

                statusMessage =尝试与服务器连接;

                的DoEvents();
                //创建一个主机和端口号的新FtpClient的对象使用
                FtpClient的FTP =新FtpClient的(MYSITE,21);

                //注册事件挂钩传输完成事件,使我们获得一个更新当传输结束
                //ftp.TransferComplete + =新的EventHandler< TransferCompleteEventArgs>(ftp_TransferComplete);

                //打开一个用户名和密码的FTP服务器的连接
                statusMessage =连接鉴定......;
                ftp.Open(用户名,密码);

                //确定pssed文件中的COM $ P $的文件大小
                statusMessage =获取文件详细信息;
                RemoteFileSize = Convert.ToInt32(ftp.GetFileSize(myFile.exe));

                ftp.TransferProgress + =新的EventHandler< TransferProgressEventArgs>(ftp_TransferProgress);
                statusMessage =从服务器下载;
                ftp.GetFile(myFile.exe,E:\\测试\\ myFile.exe,FileAction.Create);

                //关闭FTP连接
                ftp.Close();
                statusMessage =下载完成;
                返回1;
            }
            赶上(例外前)
            {
                的MessageBox.show(ex.Message.ToString());
                返回0;
            }

        }


        私人无效ftp_TransferProgress(对象发件人,TransferProgressEventArgs E)
        {
            totalBytesReceived = Convert.ToInt32(e.BytesTransferred.ToString());
            totalKbCompleted = Convert.ToInt32(totalKbCompleted + Convert.ToInt32(totalBytesReceived));
            progressBarValue = totalKbCompleted;
        }
}
 

解决方案

您从来没有开始你的体重工人。此外,丹尼尔评论,您使用的是其他BW在你的体重工人。这是没有意义的。

刚开始的体重工人的主窗口内的()  和内bw_DoWork电话FileDownloadClass.DownloadFiles()。

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().

这篇关于通过调用后台进程在一个类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆