Home
VB.NET
SyncLock Statement
This page was last reviewed on Sep 26, 2022.
Dot Net Perls
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.
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
1320870012 1320870106 1320870215 1320870309 1320870402 1320870511 1320870605 1320870714 1320870808 1320870901
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.
Thread.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.
And Imagine if many threads read a field and then change it based on some condition.
So One thread could read the field and then, before it changes it, another thread could read it. Then the first thread changes the field.
Thus By using SyncLock, the loads and stores to the field would be kept always in a valid state.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.