6

我希望我的后台工作人员将项目添加到列表框中,它似乎在调试时这样做,但列表框不显示值。我怀疑这与在后台工作线程中添加项目有关,我是否需要将这些添加到数组中,然后在期间从数组中填充列表框backgroundWorker1_RunWorkerCompleted

谢谢您的帮助。

4

6 回答 6

14

您可以像这样使用调用:

private void AddToListBox(object oo)
{
    Invoke(new MethodInvoker(
                   delegate { listBox.Items.Add(oo); }
                   ));
}
于 2008-12-15T11:00:26.923 回答
6

您可以,但您必须建议您的 Backgroundworker 报告状态,并将具有当前状态的框的输入发送到该事件。在该事件的方法中,您可以访问该框并将新值放入其中。

否则需要手动调用。

 public Form1()
        {
            InitializeComponent();

            BackgroundWorker bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                ((BackgroundWorker)sender).ReportProgress(0, i.ToString());
            }
        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            listBox1.Items.Add((string)e.UserState);
        }
于 2008-12-15T10:58:16.020 回答
1

我添加了如下函数,以便可以从主线程或后台线程将项目添加到列表框中。该线程检查是否需要调用,然后在需要时使用调用。

  delegate void AddListItemDelegate(string name,object otherInfoNeeded);

  private void
     AddListItem(
        string name,
        object otherInfoNeeded
     )
  {
     if (InvokeRequired)
     {
        BeginInvoke(new AddListItemDelegate(AddListItem), name, otherInfoNeeded
        return;
     }

     ... add code to create list box item and insert in list here ...
  }
于 2009-01-09T19:14:26.437 回答
1

您可以通过以下方式在后台线程上添加它们:

Form.Invoke

或者

Form.BeginInvoke

这是将调用从后台线程编组到主 UI 线程所必需的。但是,我很确定 BackgroundWorker 提供了一个在前台线程上自动调用的事件,您应该能够毫无问题地更新此事件。这是“ProgressChanged”,可以通过调用 ReportProgress 由后台工作进程触发。

您是否也尝试过调用.Refresh()列表框?

于 2008-12-15T10:57:02.903 回答
1

如果您尝试更新数据库。我建议从列表框中创建一个数据集。

例如,如果您为数据库中的每个项目做某事。通过创建新数据集并由 mainDataset 声明来复制数据库数据集。

例如://gridview 数据集是 dataset1

BackgroundWorker_DoWork(object sender, DoWorkArgs e)
{
     Dataset dataset2 = dataset1;
     foreach(DataGridViewRow row in GridView)
     {
         //do some work
         dataset2.Main.AddMainRow(values to add);
         dataset2.AcceptChanges();
     }
}


BackgroundWorker_WorkCompleted(object sender, DoWorkArgs e)
{
    //Forces UI thread to valitdate dataset
    dataset2.update();

    // Sets file Path
    string FilePath = "Some Path to file";

    dataset2.writexml(FilePath, XmlWriteOptions.WriteSchema);

    //if you use xml to fill your dataset filepath to write should equal path to dataset1 xml
    dataset1.Refresh();
}
于 2017-11-16T23:09:17.513 回答
0

Application.Doevents()功能将解决问题。

于 2010-08-30T09:27:29.467 回答