advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
There have been several solutions to multithreading and creating responsive user interfaces. Tell us some of the methods you have found in VB6 or your experiences with multithreading in VB.NET.
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Average Rating: 3.7/5 | Rate this item | 252 users have rated this item.
Add Multithreading to Your VB.NET Applications (cont'd)
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.
advertisement

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.

Previous Page: Passing Data Through Multithreaded Procedures  
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.
Page 1: Working with ThreadsPage 3: Passing Data Through Multithreaded Procedures
Page 2: Keep It Under ControlPage 4: Synchronizing the Threads
Please rate this item (5=best)
 1  2  3  4  5
advertisement