Name
Interlocked
Synopsis
The static members of this class provide thread safety for common built-in arithmetic operations, such as increasing and decreasing a variable by one, and exchanging variables.
If two threads increment the same variable, one thread could be
interrupted after both have retrieved the initial value of the
variable. If this happens, then both operations store the same value,
meaning that the variable has been incremented once instead of twice.
The Interlocked methods protect against this kind
of error. Increment( ) and Decrement( ) increase and decrease a variable by one, respectively,
and Exchange( ) switches two variables.
CompareExchange( ) compares the first two
variables and, if true, assigns the third value to
the first variable.
public sealed class Interlocked { // Public Static Methods public static int CompareExchange(ref intlocation1, intvalue, intcomparand); public static object CompareExchange(ref objectlocation1, objectvalue, objectcomparand); public static float CompareExchange(ref floatlocation1, floatvalue, floatcomparand); public static int Decrement(ref intlocation); public static long Decrement(ref longlocation); public static int Exchange(ref intlocation1, intvalue); public static object Exchange(ref objectlocation1, objectvalue); public static float Exchange(ref floatlocation1, floatvalue); public static int Increment(ref intlocation); public static long Increment(ref longlocation); }