C# Can I add values to a listbox with a backgroundwork thread?

拟墨画扇 提交于 2019-11-29 20:51:24

问题


I want my background worker to add items to a list box, it appears to do so when debugging but the listbox doesn't show the values. I suspect this is something to do with adding items whilst inside the background worker thread, do I need to add these to an array and then populate the list box from the array during backgroundWorker1_RunWorkerCompleted?

Thanks for the help.


回答1:


You can use Invoke like this:

private void AddToListBox(object oo)
{
    Invoke(new MethodInvoker(
                   delegate { listBox.Items.Add(oo); }
                   ));
}



回答2:


You can, but you must advise your Backgroundworker to report state, and send the input for the box with the current state to that event. In the method for that event, you can access the box and put the new value in.

Otherwise you need to invoke manually.

 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);
        }



回答3:


I add functions like the following so that I can add items to the list box from either the main thread or background threads. Thi thread checks if a Invoke is necessary and then uses Invoke if it is necessary.

  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 ...
  }



回答4:


You can add them while on a background thread via:

Form.Invoke

or

Form.BeginInvoke

which are required to marshall the call from a background thread to a main UI thread. However I'm pretty sure BackgroundWorker offers an event that automatically gets called on the Foreground thread and you should be able to update on this event without any problems. This is "ProgressChanged" which can be fired by the background worker process by calling ReportProgress.

Have you tried calling .Refresh() on the listbox as well?




回答5:


if you are trying to update a database. From a listbox i would suggest creating a dataset.

for instance, if your doing something for each item in a database. Copy the database dataset, by creating new dataset and declaring by mainDataset.

for example: // the gridview dataset is 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();
}



回答6:


Application.Doevents() function will solve the problem.



来源:https://stackoverflow.com/questions/368006/c-sharp-can-i-add-values-to-a-listbox-with-a-backgroundwork-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!