Reputation: 97
How do I invoke a for loop in VB.Net?
Example:
For Each listViewItem As ListViewItem In Me.TaskListView.Items
Me.ExecuteTask(listViewItem, False)
Next
So that needs to be invoked, but how do I go about that? I am not sure how. This is inside my background worker handler and causes an InvalidOperationException when inside it. The extra information for the error is: "Cross-thread operation not valid: Control 'TaskListView' accessed from a thread other than the thread it was created on."
The error occurs on this line:
For Each listViewItem As ListViewItem In Me.TaskListView.Items
Upvotes: 1
Views: 207
Reputation: 1776
I overcome problems with threads in winforms using the following subroutine
Public Sub GuiAsync(ByVal frm As Form, ByVal action As Action)
If action IsNot Nothing Then
If frm.InvokeRequired Then
frm.Invoke(action)
Else
action()
End If
End If
End Sub
I'd use it as follows (in case your code runs in a Form and Me is reference to the Form):
GuiAsync(Me,
Sub()
For Each listViewItem As ListViewItem In Me.TaskListView.Items
Me.ExecuteTask(listViewItem, False)
Next
End Sub)
Upvotes: 1