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.
Info The SyncLock statement uses an argument. Each call to Sub A will SyncLock on the same Object reference.
Result The statements within the SyncLock will always be sequentially run. This can help with correct threading.
Dim field As Object = New Object
' Lock on the field.
' 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)
Output notes. Environment.TickCount evaluates to a number about 100 milliseconds higher each time. This means that the statements within the SyncLock are not simultaneously run.
Detail The statements are sequentially run. The Thread.Sleep() calls evaluate one after another.