SyncLock

 <  Day Day Up  >  

The .NET Framework allows programs to execute across multiple threads of execution. A full discussion of multithreading is beyond the scope of this book, but there is a statement that helps simplify writing multithreaded applications. The SyncLock statement can be used to prevent more than one thread of execution from entering the same block of code.

For example, the following code creates two threads to fill an array.

 Imports System.Threading Module Test   Dim Array(10000) As Integer   Dim CurrentIndex As Integer = 0   Sub FillArray()     For Number As Integer = 1 to 5000       Array(CurrentIndex) = Number       CurrentIndex += 1     Next Number   End Sub   Sub Main()     Dim t1 As Thread = New Thread(AddressOf FillArray)     Dim t2 As Thread = New Thread(AddressOf FillArray)     t1.Start()     t2.Start()   End Sub End Module 

The way this code is written, the array may or may not be completely filled when the program finishes executing. If thread 1 assigns a value into a particular index, it is possible that thread 2 will read the value of CurrentIndex before thread 1 has a chance to increment the value in the variable. Thus, thread 2 will then overwrite the value that thread 1 wrote, instead of using a new index.

The SyncLock statement uses an object as a signal to prevent more than one thread of execution from entering the protected block at a time. The preceding example can be rewritten as follows , using a SyncLock statement to prevent more than one thread from updating the array at one time.

 Imports System.Threading Module Test   Dim Array(10000) As Integer   Dim CurrentIndex As Integer = 0   Sub FillArray()     SyncLock Array.SyncRoot       For Number As Integer = 1 to 5000         Array(CurrentIndex) = Number         CurrentIndex += 1       Next Number     End SyncLock   End Sub   Sub Main()     Dim t1 As Thread = New Thread(AddressOf FillArray)     Dim t2 As Thread = New Thread(AddressOf FillArray)     t1.Start()     t2.Start()   End Sub End Module 

The argument to a SyncLock statement can be an instance of any reference type ”in this example, the SyncLock statement uses the value returned by System.Array.SyncRoot as the signal. All SyncLock blocks that use the same instance will block each other, so care must be used when you are choosing what instance to use to block.

Advanced

Many collection classes like System.Array have SyncRoot properties that can be used with SyncLock to synchronize access to the collection.


 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net