With the development of multithreaded programming, the problem of simultaneous access by multiple threads to the same data arose. This led to unpredictable bugs and corrupted program states.
In Visual Basic .NET, an exclusive locking mechanism is used with the SyncLock construct to ensure that only one thread executes specific code at a time.
The solution is to use SyncLock (or Monitor.Enter/Exit) around the code that accesses shared resources to lock the object during the critical section execution.
Code example:
Private Shared Counter As Integer = 0 Private Shared ReadOnly CounterLock As New Object() Public Shared Sub IncrementCounter() SyncLock CounterLock Counter += 1 End SyncLock End Sub
Key features:
Can you use an Integer, String, or Nothing as a lock token?
No, SyncLock requires a reference object. Strings are not recommended due to possible interning, which can lead to implicit lock crossing.
What happens if different threads use different objects to lock the same variable?
There will be no synchronization, and a race condition will arise — you need to lock the exact same object.
Do you need to manually release the lock after exiting the SyncLock block?
No, unlocking happens automatically upon exiting the block, even with exceptions.
Strings are used for SyncLock in the code, and several parts of the program use the same string literals. As a result, different locks overlap, leading to unexpected deadlocks.
Pros:
Cons:
A separate ReadOnly object is declared for each critical section. Only the minimal, actually necessary part of the code is locked.
Pros:
Cons: