The Interlocked class provides methods that synchronize access to a variable that is shared by multiple threads. Interlocked operations are atomic — that is, the entire operation is a unit that cannot be interrupted by another interlocked operation on the same variable. This is important in operating systems that support preemptive multithreading, where a thread can be suspended after it loads a value from a memory address but before it has the chance to alter and store that value.
The Interlocked class provides the following operations:
The Add method adds an integer value to a variable and returns the new value of the variable.
The Exchange method performs an atomic exchange of the value in a specified variable, returning that value and replacing it with a new value. A generic overload of this method can be used to perform this exchange on a variable of any reference type. See Exchange<T>(T%, T).
The CompareExchange method also exchanges two values, but the exchange is contingent on the result of a comparison. A generic overload of this method can be used to perform this exchange on a variable of any reference type. See CompareExchange<T>(T%, T, T).
On modern processors, the methods of the Interlocked class can often be implemented by a single instruction. Therefore, they provide very high-performance synchronization and can be used to build higher-level synchronization mechanisms such as spin locks.