I want to get a control’s property from a BackgroundWorker in my form:
foreach (ListViewItem i in ListView.CheckedItems) { //error: Cross-thread operation not valid: Control 'ListView' accessed from a thread other than the thread it was created on.
//do something with i
}
Can anyone suggest the simplest and easiest method to do this?
Let me take another stab at this…
1.) Drag a ListView onto the Form
2.) Drag a BackgroundWorker onto the Form
3.) Create a method do iterate through the ListViewItem collection
4.) Add code to call LoopThroughListItems() inside the BackgroundWorker’s DoWork Event
5.) In your Form Load – execute the code on the main thread (it works) then on the backgroundWorkder thread (it fails)
6.) Modify your code to use IsInvokeRequired/Invoke
7.) Run the app again – now it works on the UI thread and the non-UI thread.
That solve the problem. The checking IsInvokeRequired/Invoking is a common pattern you’ll get used to a lot (which is why it’s included on all Controls). If you are doing it all over the place, you can do something clever and wrap it all up – as described here: Automating the InvokeRequired code pattern