Synchronization

At times, you might want to control access to a resource, such as an object’s properties or methods, so that only one thread at a time can modify or use that resource. Your object is similar to the airplane restroom discussed earlier, and the various threads are like the people waiting in line. Synchronization is provided by a lock on the object, which prevents a second thread from barging in on your object until the first thread is finished with it.

In this section you examine three synchronization mechanisms provided by the CLR: the Interlock class, the Visual Basic .NET Lock statement, and the Monitor class. But first, you need to simulate a shared resource, such as a file or printer, with a simple integer variable: counter. Rather than opening the file or accessing the printer, you’ll increment counter from each of two threads.

To start, declare the member variable and initialize it to 0:

Private counter As Integer = 0

Modify the Incrementer method to increment the counter member variable:

Public Sub Incrementer( )
    Try
        While counter < 1000
            Dim temp As Integer = counter
            temp += 1 ' increment

                           Thread.Sleep(0)

                           counter = temp
            Console.WriteLine("Thread {0}. Incrementer: {1}", _
               Thread.CurrentThread.Name, counter)
        End While

The idea here is to simulate the work that might be done with a controlled resource. Just as we might open a file, manipulate its contents, and then close it, here we read the value of counter into a temporary variable, increment the temporary variable, ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.