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.
-
2Please give more information in this question. It is possible to determine what you are asking, but it is difficult. – Merlyn Morgan-Graham Sep 03 '10 at 07:10
-
By list do you mean the collection object `System.Collections.Generic.List
` ? – ajay_whiz Sep 03 '10 at 07:13
3 Answers
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).
- 125,917
- 54
- 300
- 447
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);
}
- 2,136
- 3
- 32
- 48
If you want to add the item to the list in the DoWork-Event, you need to "invoke" the controls.
- 6,820
- 2
- 29
- 38