Sobes.tech
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 an int or long variable.
  • Decrement: Atomically decreases the value of an int or long variable.
  • Add: Atomically adds a value to an int or long variable.
  • Exchange: Atomically replaces the value of a variable with a new one and returns the previous value. Supported for various types, including int, 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, including int, 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.