This code is being run on a background thread where it's illegal to modify UI elements. The Invoke / BeginInvoke
methods are ways to schedule a piece of code to run on UI thread where elements can be modified. For example you could change your code to the following
Dim action As Action = Sub() tvNode.Nodes.Add(IO.Path.GetFileName(f))
tvNode.TreeView.Invoke(action)
This code will take the delegate instance named action
and run it on the UI thread where edits to tvNode
are allowed
Fixing the earlier Add
call is a bit trickier because there is no Control
instance on which we can call BeginInvoke
. The signature of the method will need to be updated to take a Dim control as Control
as a parameter. You can pass in the TreeView
for that parameter if you like. Once that is present the first Add
can be changed as such
Dim outerAction As Action = Sub() tvNode = tvParent.Add(IO.Path.GetFileName(d))
control.Invoke(outerAction)