GUI /进度条不从后台工作者更新

时间:2013-10-25 21:28:21

标签: c# multithreading

我一直试图让这项工作得以实现,但它不会更新GUI上的任何内容,我的应用程序存在于代码中显示的错误中。

    ListViewItem item;

    public void SetStatusStrip()
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;

        listviewTables.Columns.Add(gDatabase);

        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            try
            {
                MySqlCommand iCommand = new MySqlCommand("SHOW TABLES;", iCon);
                iRead = iCommand.ExecuteReader();
                int i = 0;
                while (iRead.Read())
                {
                    item = new ListViewItem(new[] { iRead.GetString(0) });
                    bw.ReportProgress(i);
                    i++;
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("There was an error getting tables from the database: " + gDatabase + ".\n\nError Dump:\n" + ex, "MySQL Error!");
                return;
            }
        });

        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            progressBar1.Value = args.ProgressPercentage;
            listviewTables.Items.Add(item); // I get error here: System.ArgumentException
        });

        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            progressBar1.Value = 0;

            // Finished.
        });

        bw.RunWorkerAsync();
    }

1 个答案:

答案 0 :(得分:2)

我同意LarsTech。

在ReportProgress();

中传递ListViewItem
            while (iRead.Read())
            {
                bw.ReportProgress(i, new ListViewItem(new[] { iRead.GetString(0) }));
                i++;
            }

然后将ProgressChanged()中的UserState强制转换回ListViewItem:

    bw.ProgressChanged += new ProgressChangedEventHandler(
    delegate(object o, ProgressChangedEventArgs args)
    {
        progressBar1.Value = args.ProgressPercentage;
        listviewTables.Items.Add((ListViewItem)args.UserState);
    });

请注意,我没有使用你的全局变量“item”,这不是一个好主意。