Search code examples
c#multithreadingthread-safetyinterlocked

Is using Interlocked in C# get and set thread safe?


Is it possible to get a thread safe property by using Interlocked in the property accessors?

Example:

public class A()
{
    private static long count;

    public static long Count
    {
        get
        {
            return Interlocked.Read(ref count);
        }
        set
        {
           Interlocked.Exchange(ref count, value); 
        }
    }
}

Solution

  • When the above example is run, the execution behavior of the get and set accessors is linearizable. Without the use of Interlocked, the execution behavior of the get and set accessors is somewhere between weak consistency and sequential consistency (i.e. only guaranteed to exhibit weak consistency).

    When run as a 64-bit process, the same could be accomplished by marking the field volatile and using a simple return statement and assignment operator. When run as a 32-bit process, however, the operations on a volatile 64-bit field are not guaranteed to be atomic, so the use of Interlocked is required to ensure atomicity.