Middle
What is Interlocked in C#?
sobes.tech AI
Answer from AI
Interlocked is a class in the System.Threading namespace that provides atomic operations for variables that may be shared across multiple threads. An atomic operation is one that is guaranteed to be completed entirely or not at all, even when accessed concurrently from different threads.
The main atomic operations provided by Interlocked include:
Increment: Atomically increases the value of anintorlongvariable.Decrement: Atomically decreases the value of anintorlongvariable.Add: Atomically adds a value to anintorlongvariable.Exchange: Atomically replaces the value of a variable with a new one and returns the previous value. Supported for various types, includingint,long,float,double, and reference types.CompareExchange: Atomically compares the value of a variable with a specified value. If they are equal, it replaces the variable's value with a new one. Returns the previous value of the variable. Supported for various types, includingint,long,float,double, and reference types.
Using Interlocked helps avoid data races that can occur when working with shared variables from different threads without locks. This makes the code more reliable and efficient in scenarios where only atomic access to a single variable is required, as Interlocked generally incurs no overhead from mutexes or locks.