You can use a separate thread to, for example, fill a long ListBox without making the user wait. You must create a delegate and use the Invoke method on the form (or a control) so that the separate thread can safely update the UI. Here is an example that fills a ListBox with all customers from a separate thread. Note that the data comes from a simple Middle-Tier component, which is beyond the scope of this post.
Imports System.Threading
Public Class frmThreadUI
Inherits System.Windows.Forms.Form
Private Sub LoadCustomers()
' this function will execute on a separate thread.
Dim dsCustomers As CustomerSet = Customer.GetAll()
' call our threadsafe DisplayCustomers from our separate thread
DisplayCustomers_ThreadSafe(dsCustomers)
End Sub
Private Sub DisplayCustomers_ThreadSafe(ByVal dsCustomers As CustomerSet)
' this is a threadsafe method called from the separate worker thread
Dim oDel As New DisplayCustomersDelegate(AddressOf Me.DisplayCustomers)
Dim args() As DataSet = {dsCustomers}
Me.Invoke(oDel, args)
End Sub
' define a delegate (signature) for the callback.
Delegate Sub DisplayCustomersDelegate(ByVal dsCustomers As CustomerSet)
Private Sub DisplayCustomers(ByVal dsCustomers As CustomerSet)
' display the customer list in the ListBox
lstCustomers.DataSource = dsCustomers.Tables(0)
lstCustomers.DisplayMember = "CompanyName"
lstCustomers.ValueMember = "CustomerId"
End Sub
Private Sub frmThreadUI_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
' give a "loading" message.
lstCustomers.Items.Add("Loading... please wait.")
' kick off a separate thread to load the Customers into a ListBox
Dim oTS As New ThreadStart(AddressOf LoadCustomers)
Dim oThread As Thread = New Thread(oTS)
oThread.Start()
End Sub
End Class