The interlocked class encapsulates synchronization primitives and is used to provide atomic operations to variables that are shared across threads. It provides methods such as Increment, Decrement, Add, Exchange, and CompareExchange.
Consider the following code, which tries to increment a counter inside a parallel loop:
Parallel.For(1, 1000, i =>
{
Thread.Sleep(100);
_counter++;
});
Console.WriteLine($"Value for counter should be 999 and
is {_counter}");
If we run this code, we will see the following output:
As you can see, the expected value and the actual value do not match. This is because of the race condition among the threads, which has arisen because the thread wants to read a value from a variable to which the value has been written but not yet committed.
We can modify the preceding code...