
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1016
|
Chapter 18: Threading and Synchronization
{
return (numericField);
}
}
Solution
NoSafeMemberAccess could be used in a multithreaded application, and therefore it
must be made thread-safe. Consider what would occur if multiple threads were call-
ing the
IncrementNumericField method at the same time. It is possible that two calls
could occur to
IncrementNumericField while the numericField is updated only once.
In order to protect against this, you will modify this class by creating an object that
you can lock against in critical sections of the code:
public static class SaferMemberAccess
{
private static int numericField = 1;
private static object syncObj = new object( );
public static void IncrementNumericField( )
{
lock(syncObj)
{
++numericField;
}
}
public static void ModifyNumericField(int newValue)
{
lock(syncObj)
{
numericField = newValue;
}
}
public static int ReadNumericField( )
{
lock (syncObj)
{
return (numericField);
}
}
}
Using the lock statement on the syncObj object lets you synchronize access to the
numericField member. This now makes all three methods safe for multithreaded
access.
Discussion
Marking a block of code as a critical section is done using the lock keyword. The
lock keyword should not be used on a public type or on an instance out of the