To synchronize threads, you can use the SyncLock statement. This statement lets you block access to shared resources by other threads. Here's how you use this statement:
SyncLock Expression [sensitive code] End SyncLock
To use that statement, you pass it an expression to use to lock access, such as an object. (The type of this expression must be a reference type, such as a class, a module, an array, or an interface.) For example, if you lock an object, no other thread can access the object until it's unlocked.
For example, we saw how to use SyncLock in the SynchronizeThreads example in the In Depth section of this chapter. In that example, we used two threads to increment a value. The two threads paused for a millisecond each before updating the incremented value, which meant that the threads interfered with each other, as discussed in the In Depth section of this chapter. By using SyncLock, we were able to lock the object being updated, which stopped the threads from interfering with each other:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Thread1.Start() Thread2.Start() ⋮ End Sub Private Sub Counter1() Dim LoopIndex As Integer For LoopIndex = 1 To 100 SyncLock c Dim temp = c.Total Thread1.Sleep(1) c.Total = temp + 1 End SyncLock Next LoopIndex End Sub Private Sub Counter2() Dim LoopIndex As Integer For LoopIndex = 1 To 100 SyncLock c Dim temp = c.Total Thread2.Sleep(1) c.Total = temp + 1 End SyncLock Next LoopIndex End Sub
Microsoft recommends that you don't use the SyncLock statement to lock threads that work with controls or forms.
For more on this example, see the In Depth section of this chapter.