-1

how to maintain a foreground thread along with background thread. if i try to add items to the list in do work, it's giving me a cross thread exception.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Preeti
  • 1,386
  • 8
  • 57
  • 112

3 Answers3

8

In general, UI updates may only be performed from the UI thread itself.

The mechanism for doing this with a BackgroundWorker is to call the worker's ReportProgress method (make sure WorkerReportsProgress = true). This method will raise the ProgressChanged event, to be handled by the UI thread.

So if you want to add items to a ListBox control, for example, based on some work your BackgroundWorker is doing, call ReportProgress and pass whatever data you need as a parameter. This data will be stored in the UserState property of the ProgressChangedEventArgs supplied by the event. Your event handler can take this data and populate the ListBox with it.

Alternately, you can add everything at the end by handling the worker's RunWorkerCompleted event. If the work performed by your worker does not take all that long, this is often preferable as it's simpler and it stresses the UI less (with fewer discrete updates to perform).

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
0

You can fire event that do the work of adding items to the list as shown in the below example using ListView.

ListViewItem _listViewItem;

private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
    //your loop to get list view item
    _listViewItem = new ListViewItem(mytext) {tag = mytagobject);
    _listViewItem.SubItems.Add(mysubitemtext);
    Invoke(new EventHandler(UpdateUiEvent), new[] { sender, e });
}

void UpdateUiEvent(object sender, EventArgs e)
{
    listView1.Items.Add(_listViewItem);
}
Ravi Patel
  • 2,136
  • 3
  • 32
  • 48
0

If you want to add the item to the list in the DoWork-Event, you need to "invoke" the controls.

Look here for more details.

yan.kun
  • 6,820
  • 2
  • 29
  • 38