C#BackgroundWorker和ProgressBar问题

时间:2017-02-09 06:07:41

标签: c# multithreading backgroundworker

我有两个文件。一个包含DataProgressBar类型的变量,并在加载自己的组件之前调用startAsyncWorker()方法。另一个是下面显示的DataProgressBar。当我运行我的程序并在其他文件中调用startAsyncWorker()时的行为

EXPECTED:显示带有进度条的小窗口,在执行WorkerDatabaseInsertion中的工作时从0加载到100。然后,当我完成包含DataProgressBar的第一个类文件时,将继续执行下一条指令。

经验丰富:显示带有进度条的小窗口,未对UI进行任何更改,线程似乎冻结,因为没有显示输出或处理证据。我关闭窗口,调用文件恢复。

public partial class DataProgressBar : Window
    {
        private BackgroundWorker bgw;
        private String _path;
        private LFPReader _lfp;
        private Access db;


            public DataProgressBar(String p, LFPReader reader, Access database)
            {
                InitializeComponent();
                /* Set private class level variables */
                _path = p;
                _lfp = reader;
                db = database;
                db.open();
                /* Set up worker and progressbar */
                bgw = new BackgroundWorker();
                SetUpWorker(bgw);
                progressbar.Maximum = 100;
                progressbar.Minimum = 0;
                progressbar.Value = 0;
            }

            public void startAsyncWorker()
            {
                if(bgw.IsBusy != true)
                {
                    bgw.RunWorkerAsync();
                }
            }

            /// <summary>
            /// This methods exists for completeness, but we will
            /// probably not need to directly cancel the worker from here.
            /// --Kurtpr
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void cancelAsyncWorker(object sender, EventArgs e)
            {
                if (bgw.WorkerSupportsCancellation == true)
                {
                    bgw.CancelAsync();
                }
            }

            private void SetUpWorker(BackgroundWorker worker)
            {
                worker.WorkerReportsProgress = true; // we need this in order to update the UI
                worker.WorkerSupportsCancellation = true; // Not sure why, but we may need this to cancel

                worker.DoWork += new DoWorkEventHandler(WorkerDatabaseInsertion);
                worker.ProgressChanged += new ProgressChangedEventHandler(WorkerProgressChanged);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerBurnNotice);
            }

            private void WorkerDatabaseInsertion(object sender, DoWorkEventArgs e) {
                BackgroundWorker worker = sender as BackgroundWorker;
                ImageInfo ImageData = new ImageDB.ImageInfo();
                double size = _lfp.GetImageData().ToArray().Length;
                int index = 0;
                //_path is setup in loadAsLFP() before this call.
                foreach (var image in _lfp.GetImageData())
                {
                    index++;
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    image.FullPath = Path.Combine(_path, image.FullPath);
                    ImageData.Add(new ImageDB(image));
                    db.insertImage(new ImageDB(image));
                    worker.ReportProgress((int)(index/size));
                }
            }

            private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                Console.WriteLine("Hello");
                progressbar.Value = e.ProgressPercentage;
            }

            private void WorkerBurnNotice(object sender, RunWorkerCompletedEventArgs e)
            {
                db.close();
            }
        }

我怀疑我对BackgroundWorker的一个基本方面是错误的。我的逻辑错在哪里?

编辑以下是调用和创建DataProgressBar对象的代码。

private void createDb(string filePath, LFPReader lfp)
        {
            //Set up LFP related objects.
            ImageData = new ImageDB.ImageInfo();

            //create database file.
            filePath = filePath.Replace(".lfp", ".mdb").Replace(".LFP", ".mdb");
            _lfpName = filePath; // update to use the database file
            Access db = new Access(filePath.Replace(".lfp", ".mdb"));
            db.createDatabase();

            //used for calculating progress of creating this new database.
            var progressbar = new DataProgressBar(_path, lfp, db);
            progressbar.ShowDialog();
            progressbar.startAsyncWorker();

            CurImage = ImageData.First().FullPath;
            //Make sure that data context is set for these images.
            DataContext = ImageData;

        }

1 个答案:

答案 0 :(得分:3)

我认为你的进度计算逻辑是错误的。

worker.ReportProgress((int)(index/size));

此行始终将进度报告为0。因此,您的进度条将始终位于0位置。

相反,请使用以下报告百分比进度。

worker.ReportProgress((int)(index*100/size));

<强>更新 您共享的代码似乎是正确的。 我认为问题在于您实施进度条的方式。

我想你是从主线程调用startAsyncWorker方法,如下所示;

var dpb = new DataProgressBar(p, reader, database);
dpb.startAsyncWorker();

在调出上面两行之后,你的主线程应该是免费的。

这意味着,以下代码会导致进度条冻结50秒,因为即使您的DoWork运行正常,UI也不会更新,因为主线程不是免费的。

var dpb = new DataProgressBar(p, reader, database);
dpb.startAsyncWorker();
Thread.Sleep(50000);               //Main thread is busy for 50 seconds

更新2:

真正的问题在于以下几行;

var progressbar = new DataProgressBar(_path, lfp, db);
progressbar.ShowDialog();
progressbar.startAsyncWorker();

实际上ShowDialog()方法将DataProgressBar显示为模态对话框。这意味着,除非您关闭该对话框,否则控件不会转到下一行。

您的问题应该使用以下代码解决;

var progressbar = new DataProgressBar(_path, lfp, db);
progressbar.startAsyncWorker();
progressbar.ShowDialog();

首先启动后台工作程序,然后显示DataProgressBar对话框。