Browse DevX
Sign up for e-mail newsletters from DevX


Add Multithreading to Your VB.NET Applications-4 : Page 4




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

Matthew Arnheiter is a Senior Consultant at GoAmerica Communications (www.goamerica.net) of Hackensack, NJ. He is also the author of "The Visual Basic Developer's Guide to Design Patterns and UML" (Sybex, 2000). He can be reached here.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date