GUI/进度条未从后台工作人员更新

本文关键字:后台 工作人员 更新 GUI | 更新日期: 2023-09-27 18:36:59

我一直在尝试完成这项工作,但它不会更新 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();
    }

GUI/进度条未从后台工作人员更新

我同意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",这是一个坏主意。