I've been reading around trying to find out why I'd be getting this exception to no avail. I hope someone has seen this before:
I'm using Visual Basic 2010.
Briefly, I have a "Settings Panel" form which takes a while to create (it contains a lot of labels and textboxes), so I create it in another thread.
After it's loaded, it can be viewed by clicking a button which changes the form's visibility to True. I use the following subroutine to handle invokes for my controls:
Public Sub InvokeControl(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T))
If Control.InvokeRequired Then
Control.Invoke(New Action(Of T, Action(Of T))(AddressOf InvokeControl), New Object() {Control, Action})
Else
Action(Control)
End If
End Sub
Here's the relevant part of my main code (SettingsTable inherits TableLayoutPanel and HelperForm inherits Form):
Public Class ch4cp
Public RecipeTable As SettingsTable
Public WithEvents SettingsWindow As HelperForm
Private Sub ch4cp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
PanelCreatorThread = New Threading.Thread(AddressOf CreateStartupPanels)
PanelCreatorThread.Start()
End Sub
Private Sub CreateStartupPanels()
SettingsWindow = New HelperForm("Settings Panel")
SettingsTable = New SettingsTable
SettingsTable.Create()
SettingsWindow.Controls.Add(SettingsTable)
End Sub
Private Sub ViewSettingsPanel_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewSettingsPanel.CheckedChanged
InvokeControl(SettingsWindow, Sub(x) x.Visible = ViewSettingsPanel.Checked)
End Sub
The SettingsTable.Create() method generates a bunch of Labels and TextBoxes based on the contents of the application settings and adds them to the SettingsTable.
When I click on the ViewSettingsPanel checkbox, I get a cross-thread violation error. Any ideas? I would really appreciate it.