I got a book about programming in C#. There is an example. Let me copy and paste the context.
...Introduced the usage of Interlocked(omitted here).
You can also use the CompareExchange method. This method first checks to see whether the expected value is there; if it is, it replaces it with another value.
Listing 1-41 shows what can go wrong when comparing and exchanging a value in a nonatomic operation.
LISTING 1-41 Compare and exchange as a nonatomic operation
class Program
{
static int value = 1;
static void Main(string[] args)
{
Task t1 = Task.Run(() =>
{
if(value==1)
{
// Removing the following line will change the output
Thread.Sleep(1000);
value = 2;
}
});
Task t2 = Task.Run(() =>
{
value = 3;
});
Task.WaitAll(t1, t2); // Displays 2
Console.WriteLine(value);
}
}
Task t1 starts running and sees that value is equal to 1. At the same time, t2 changes the value to 3 and then t1 changes it back to 2. To avoid this, you can use the following Interlocked statement:
Interlocked.CompareExchange(ref value, newValue, compareTo);
This makes sure that comparing the value and exchanging it for a new one is an atomic operation. This way, no other thread can change the value between comparing and exchanging it.
The book doesn't provide further details and just ends this section at this point.
My question is how to apply Interlocked.CompareExchange(ref value, newValue, compareTo);
to the code?