VB.NET SyncLock StatementUse the SyncLock statement. Import System.Threading and implement thread-safe logic.
Threads 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.Keywords
To get started we consider this VB.NET Program. 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.
VB.NET program that uses SyncLock
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)
In the output,
we see that the Environment.TickCount property evaluates to a number about 100 milliseconds higher each time. This means that the statements within the SyncLock are not simultaneously run.
Instead: The statements are sequentially run. The Thread.Sleep() calls evaluate one after another.Sleep
Discussion. 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. Imagine if many threads read a field and then change it based on some condition.
could read the field and then, before it changes it, another thread could read it. Then the first thread changes the field. Now the second thread could be left with invalid data—and this could propagate.
But: By using SyncLock, the loads and stores to the field would be kept always in a valid state.
Summary. The SyncLock statement allows only 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.