SyncLock
Threads in VB.NET programs run all at the same time. This causes problems when they access sensitive parts of code—it creates conflicts.
With SyncLock
, we restrict all except one thread from running, based on a lock object. This keyword is the same as the "lock" keyword in the C# language.
In Main
, we iterate through ten numbers and create a new Thread each time. When each thread starts, control flow moves to the Sub
A. In Sub
A, we encounter a SyncLock
.
SyncLock
statement uses an argument. Each call to Sub
A will SyncLock
on the same Object reference.SyncLock
will always be sequentially run. This can help with correct threading.Imports System.Threading Module Module1 Dim field As Object = New Object Sub A() ' Lock on the field. SyncLock field Thread.Sleep(100) Console.WriteLine(Environment.TickCount) End SyncLock End Sub Sub Main() ' Create ten new threads. ' ... They finish one after the other. For i As Integer = 1 To 10 ' Call A() in new thread. Dim ts As ThreadStart = New ThreadStart(AddressOf A) Dim t As Thread = New Thread(ts) t.Start() Next End Sub End Module1320870012 1320870106 1320870215 1320870309 1320870402 1320870511 1320870605 1320870714 1320870808 1320870901
Environment.TickCount
evaluates to a number about 100 milliseconds higher each time. This means that the statements within the SyncLock
are not simultaneously run.
Thread.Sleep()
calls evaluate one after another.It is important to use SyncLock
when accessing fields from multiple threads. If you do not, it is possible for fields to end up in an invalid state.
SyncLock
, the loads and stores to the field would be kept always in a valid state.SyncLock
allows one thread to execute the code at once. The runtime uses the identity of the object argument of SyncLock
. That identity is used to restrict access.