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’ll examine three synchronization mechanisms provided by the CLR: the Interlock class, the C# lock statement, and the Monitor class. But first, you’ll 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:

int counter = 0;

Modify the Incrementer method to increment the counter member variable:

public void Incrementer(  )
{
   try
   {
      while (counter < 1000)
      {
         int temp = counter;
         temp++; // increment

         // simulate some work in this method
         Thread.Sleep(1);

         // assign the Incremented value
         // to the counter variable
         // and display the results
         counter = temp;
         Console.WriteLine(
            "Thread {0}. Incrementer: {1}", 
            Thread.CurrentThread.Name,
            counter);
      }
   }

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 ...

Get Programming C# 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.