So do we not need to implement our own Swap method? Is Interlocked.Exchange the intended Swap method from Microsoft?
No reason why not, although it's not completely general purpose:
- It's guaranteed to be atomic, i.e. thread-safe; you probably don't need this most of the time.
- Interlocked.Exchange only works on reference types: there are different overloads for int, long, IntPtr, float and double.
I would prefer this to your own Swap method.
Interlocked.Exchange provides a way to handle exchanges atomically. It's basically the managed wrapper for InterlockedExchnagedPointer.
There are many advantages to using this over your own swap method, at least in threaded situations. Since this is a single, atomic operation, it is much safer in a threaded application.
Don't use it for simple swap operations since it will serialize access to memory, probably invalidate cpu caches and stall the cpu(s). If you need to manage concurrency, there are better ways to do it than swaps in .NET.
swap(a,b)->t=a,a=b,b=t : 3 transactions which can be split
using interlocked swap(a,b)->interlockedExchange(a,interlockedExhcange(b,a)); the problem is not resolved as it is still 2 operations which can be split.
it seems for the moment the best way to get an interlockedSwap is to put a critical section around to ensure the steps don't get split.
Looking at this a different way, if T was a pair< a, b >, you could construct a new pair with the values swapped, and then use interlockedExchange of T - however the actions of building the pair to swap in may suffer data sheering if somebody else is swapping, or already be swapped when you try and do the exchange. So again you need a critical section around to ensure the steps don't get split.
Interlocked.Exchange doesn't swap its arguments. Only the first argument is changed, not the second argument. The "exchange" refers to exchanging a new value for the first argument for its old value.
This makes it a very poor choice for a swap function.