I’ve got an application with a ListView and I want to loop through each item in the ListView. But I want to do this in a separate thread.
This is a very simple version of the code – but its error is the same:
Private Sub StartToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartToolStripMenuItem.Click
pingThread = New Thread(AddressOf loopingRoutine)
pingThread.Start()
End Sub
Public Sub loopingRoutine()
For Each item As ListViewItem In ListView1.Items
MsgBox(item.Text)
Next
End Sub
That causes the following error:
Cross-thread operation not valid: Control ‘ListView1’ accessed from a thread other than the thread it was created on.
Why is this the case? I’ve never had this problem before when using DataGridViews.
Can anyone shed some light on it?
You cannot access WinForms items from a background thread. They are affinitized to the UI thread. If you’ve been able to do this in the past with a different type then you were unlucky that it worked.
Whenever you want to work with a specific controls you need to
Invokeback to the UI thread to access it’s members. Doing an action such as looping on the members is just not possible on the background thread.