December 2019
Intermediate to advanced
346 pages
9h 8m
English
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 ...
Read now
Unlock full access