C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Instead: The statements are sequentially run. The Thread.Sleep() calls evaluate one after another.
SleepBut: By using SyncLock, the loads and stores to the field would be kept always in a valid state.