VB.NET•Add Nodes to the TreeView

Listing 6. It's possible to load the nodes into the TreeView asynchronously, using the same pattern to update the TreeView nodes as you used on the ProgressBar. This gives your app's main UI the boost it needs to satisfy demanding end users.

Public Delegate Sub UpdateUI _
   (ByRef nCurrent As TreeNode, _
   ByRef nParent As TreeNode, _
   ByRef nChild As TreeNode)

Private Sub OnAddNode _
   (ByVal nCurrent As TreeNode, _
    ByVal nParent As TreeNode, _
    ByVal nChild As TreeNode)

   Dim ui As New UpdateUI _
      (AddressOf AddTreeItem)
   Dim args As Object() = _
      {nCurrent, nParent, nChild}

   If Me.TreeView1.InvokeRequired Then
      Me.BeginInvoke(ui, args)
      Console.WriteLine _
         (Thread.CurrentThread.Name)
   Else
      AddTreeItem _
         (nCurrent, nParent, nChild)
   End If

End Sub

Private Sub AddTreeItem _
   (ByRef nCurrent As TreeNode, _
   ByRef nParent As TreeNode, _
   ByRef nChild As TreeNode)

   ' code to add the nodes to the TreeView

   Console.WriteLine _
      (Thread.CurrentThread.Name)

End Sub