O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.2. Providing Thread Safe Access to Class Members

Problem

You need to provide thread-safe access through accessor functions to an internal member variable.

The following NoSafeMemberAccess class shows three methods: ReadNumericField, IncrementNumericField and ModifyNumericField. While all of these methods access the internal numericField member, the access is currently not safe for multithreaded access:

public sealed class NoSafeMemberAccess
{
    private NoSafeMemberAccess ( ) {}

    private static int numericField = 1;

    public static void IncrementNumericField( ) 
    {
        ++numericField;
    }

    public static void ModifyNumericField(int newValue) 
    {
        numericField = newValue;
    }

    public static int ReadNumericField( )
    {
        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 calling 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, we will modify this class by creating an object that we can lock against in critical sections:

public sealed class SaferMemberAccess
{
    private 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) { numericField ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required