Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
[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.
Inheritance Hierarchy
System. . :: . .Object
System.Threading..::..Interlocked
Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
Syntax
'Declaration
Public NotInheritable Class Interlocked
public static class Interlocked
public ref class Interlocked abstract sealed
[<AbstractClass>]
[<Sealed>]
type Interlocked = class end
public final class Interlocked
The Interlocked type exposes the following members.
Methods
Name | Description | |
---|---|---|
![]() ![]() |
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. |
Top
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 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.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.