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.