I assume you're considering code like this:
using System;
using System.Threading;
class Test
{
static int x = 1;
static int y = 2;
static void Main()
{
x = Interlocked.Exchange(ref y, 5);
}
}
In that case, no, the operation isn't atomic. In IL, there are two separate actions:
- Calling the method
- Copying the value from the notional stack to the field
It would be entirely possible for another thread to "see" y
become 5 before the return value of Interlocked.Exchange
was stored in x
.
Personally, if I were looking at something where you need multiple field values to be changed atomically, I'd be considering locks instead of atomic lock-free operations.