Here's my understanding of the code (in single-threaded land):
static int CompareExchange(ref int location1, int value, int comparand)
{
var valueToReturn = location1;
if (location1 == comparand)
{
location1 = value;
}
return valueToReturn;
}
Taken from the docs here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange
Parameters
- location1 (Int32)
The destination, whose value is compared with comparand and possibly replaced.
- value (Int32)
The value that replaces the destination value if the comparison results in equality.
- comparand (Int32)
The value that is compared to the value at location1.
- Returns (Int32)
The original value in location1.
Remarks
If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.