Synchronizing the Threads
VB.NET contains a few statements to provide synchronization of threads. In the Square example, you would want to synchronize the thread performing the calculation in order to wait for the calculation to complete so you can retrieve the result. Another example would be if you sort an array on a different thread and you would wait for that process to complete before using the array. To perform these synchronizations, VB.NET provides the SyncLockEnd SyncLock statement and the Thread.Join method.
SyncLock gains an exclusive lock to an object reference that is passed to it. By gaining this exclusive lock you can ensure that multiple threads are not accessing shared data or that the code is executing on multiple threads. A convenient object to use in order to gain a lock is the System.Type object associated with each class. The System.Type object can be retrieved using the GetType method:
Public Sub CalcSquare()
SyncLock GetType(SquareClass)
Square = Value * Value
End SyncLock
End Sub
Lastly, the Thread.Join method allows you to wait for a specific amount of time until a thread has completed. If the thread completes before the timeout that you specify, Thread.Join returns True, otherwise it returns False. In the square sample, if we did not want to raise events, we could call the Thread.Join method to determine if the calculation has finished. The code would look like the following:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim oSquare As New SquareClass()
t = New Thread(AddressOf oSquare.CalcSquare)
oSquare.Value = 30
t.Start()
If t.Join(500) Then
MsgBox(oSquare.Square)
End If
End Sub
The one thing to note with this method is that the procedure handling the event, in this case SquareEventHandler, will run within the thread that raised the event. It does not run within the thread from which the form is executing.