See Also: Interlocked Members
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.