System.Threading.Interlocked Class

Provides atomic operations for variables that are shared by multiple threads.

See Also: Interlocked Members

Syntax

public static class Interlocked

Remarks

The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors. The members of this class do not throw exceptions.

The Interlocked.Increment(Int32@) and Interlocked.Decrement(Int32@) methods increment or decrement a variable and store the resulting value in a single operation. On most computers, incrementing a variable is not an atomic operation, requiring the following steps:

[The 'ordered' type of list has not been implemented in the ECMA stylesheet.]

If you do not use Interlocked.Increment(Int32@) and Interlocked.Decrement(Int32@), a thread can be preempted after executing the first two steps. Another thread can then execute all three steps. When the first thread resumes execution, it overwrites the value in the instance variable, and the effect of the increment or decrement performed by the second thread is lost.

The Interlocked.Exchange(Int32@, int) method atomically exchanges the values of the specified variables. The Interlocked.CompareExchange(Int32@, int, int) method combines two operations: comparing two values and storing a third value in one of the variables, based on the outcome of the comparison. The compare and exchange operations are performed as an atomic operation.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Requirements

Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0