I need some help trying to figure what I’m doing wrong. I’m trying to get a collection of items from the system log on a separate thread to keep the form from being frozen during the collection process. I can get the background worker to grab them all, but I am having some issues add them to the ListBox on the form.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
{
listBox1.Items.Add(
entry.EntryType.ToString() + " - " +
entry.TimeWritten + " - " +
entry.Source);
}
}
Obviously this doesn’t work as expected, since there are 2 separate threads, and you can’t change objects on different threads, as I have found out. So, If someone could guide me in the right direction, I would be thankful.
You should not access UI elements from non-UI thread. Run
ReportProgress, which will be synced with UI thread.Make sure you enable
WorkerReportsProgress.and subscribed to
ProgressChangedAnother approach is to call
Control.InvokeinsideBut with this approach you don’t need
BackgroundWorkeras whole point of it is to useProgressChangedandRunWorkerCompletedevent handler which are synced with the UI thread.