Threading: Passing Parameters, Returning Values and Accessing Controls

Derek Stone

Exalted One
Joined
Nov 17, 2002
Messages
1,875
Location
Rhode Island, USA
As it stands now you're probably launching new threads from your application's main class.

Visual Basic:
Public Class Form1
	Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

		Dim tThread As New Thread(AddressOf SecondaryThread)
		tThread.Start()
	End Sub

	Private Sub SecondaryThread()
		MessageBox.Show("Code executing in new thread", Application.ProductName)
	End Sub
End Class

The above snippet works just fine as long as no parameters need to be passed to the thread. In the likely event that parameters do need to be passed however the code needs to be reworked. Since methods called from a thread continue to execute on the same thread, even if they are located in a different class, we can rearrange the order of execution a bit to suit our needs. The ThreadArguments class, declared below, exposes the ThreadDelegate property that can be set to the location of the sub or function that's to be executed on a new thread. When the thread executes the Start method is passed as the sub to be placed on a new thread, which in turn passes execution along with a single parameter to our TertiaryThread function.

Visual Basic:
Public Class Form1
	Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim ta As New ThreadArguments()

		ta.Message = "Custom message"

		ta.ThreadDelegate = AddressOf TertiaryThread

		Dim tThread As New Thread(AddressOf ta.Start)
		tThread.Start()
	End Sub

	Delegate Sub TertiaryThreadDelegate(ByVal Message As String)

	Private Class ThreadArguments
		Public Message As String

		Public ThreadDelegate As TertiaryThreadDelegate

		Public Sub Start()
			ThreadDelegate(Message)
		End Sub
	End Class

	Private Sub TertiaryThread(ByVal Message As String)
		MessageBox.Show(Message, Application.ProductName)
	End Function

End Class

The concept here is to pass the execution from a sub that can't handle parameters to one that can. We initialize a new instance of the ThreadArguments class for each thread we create so that the parameter(s) we pass remains unique an isolated from all other threads. Keep in mind this code can be extended to handle multiple parameters and return values, the latter which we'll look at next.

Download example application
 
Back
Top