VB.NET SyncLock Statement

Use the SyncLock statement. Import System.Threading and implement thread-safe logic.

SyncLock. 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

Example. 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 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 Module Output 1320870012 1320870106 1320870215 1320870309 1320870402 1320870511 1320870605 1320870714 1320870808 1320870901

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.


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.

One thread 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.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to