How do I atomically swap 2 ints in C#?

后端 未结 8 767
执念已碎
执念已碎 2020-11-29 06:50

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

8条回答
  •  温柔的废话
    2020-11-29 06:56

    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.

提交回复
热议问题