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 helps the developer avoid having a second thread barge in on your object until the first thread is finished with it.
This section examines three synchronization mechanisms: the Interlock
class, the C# lock
statement, and the Monitor
class. But first, you need to create a shared resource (often a file or printer); in this case, a simple integer variable: counter
. You will 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 you might open a file, manipulate its contents, and then close it, here, you read the value of counter
into a temporary variable, ...
Get Programming C# 3.0, 5th 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.