[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
Provides atomic operations for variables that are shared by multiple threads.
Assembly: mscorlib (in mscorlib.dll)
Thetype exposes the following members.
|CompareExchange||Compares two 32-bit signed integers for equality and, if they are equal, replaces one of the values.|
|Decrement||Decrements a specified variable and stores the result, as an atomic operation.|
|Exchange||Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.|
|Increment||Increments a specified variable and stores the result, as an atomic operation.|
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 Increment and Decrement 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:
Load a value from an instance variable into a register.
Increment or decrement the value.
Store the value in the instance variable.
If you do not use Increment and Decrement, 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 Exchange method atomically exchanges the values of the specified variables. The CompareExchange 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.