hi,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.
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).
If you want to add the item to the list in the DoWork-Event, you need to "invoke" the controls.