How to correctly read an Interlocked.Increment’ed int field?

If you want to guarantee that the other thread will read the latest value, you must use Thread.VolatileRead(). (*)

The read operation itself is atomic so that will not cause any problems but without volatile read you may get old value from the cache or compiler may optimize your code and eliminate the read operation altogether. From the compiler’s point of view it is enough that the code works in single threaded environment. Volatile operations and memory barriers are used to limit the compiler’s ability to optimize and reorder the code.

There are several participants that can alter the code: compiler, JIT-compiler and CPU. It does not really matter which one of them shows that your code is broken. The only important thing is the .NET memory model as it specifies the rules that must be obeyed by all participants.

(*) Thread.VolatileRead() does not really get the latest value. It will read the value and add a memory barrier after the read. The first volatile read may get cached value but the second would get an updated value because the memory barrier of the first volatile read has forced a cache update if it was necessary. In practice this detail has little importance when writing the code.

Leave a Comment