What (if any) is the C# equivalent of the x86 asm xchg instruction?
With that command, which imo is a genuine exchange (unlike Interlocked.Exchange
), I
Interlocked.Exchange is really the only thing you can do:
var x = Interlocked.Exchange(a, b);
Interlocked.Exchange(b, x);
You are correct that this will not be atomic, but with a local variable used you are guaranteed that the values are consistent as long as both lines execute. Your other options are unsafe code (for using pointers), using p/invoke to a native library, or redesigning so that it's no longer required.