Assignment vs Interlocked.Exchange

It's important in multi threaded programs to understand the difference between an assigment operation and Interlocked.Exchange when you are dealing with shared references (memory).

The .NET ECMA spec in section 12.6.6 sets that reference assigment (and any other platform word size set) will be an atomic operation (when memory is properly aligned).  I've seen some devs sight this when using simple assigment operations on a shared reference.  The problem is the assigment is atomic but it makes no gaurantees about when the update will reach other threads (i.e. memory locations, caches).  So it will cause no apparent errors but the change may not be immediately visible to other threads

Interlocked.Exchange while atomic also gaurantees that the change will be propagated to all other threads in the program.  It's a bit slower though. 

Comments (0)

Skip to main content