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

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