Example "volatile" preventing compiler optimization in C #?

From what I understand, a “mutable” modifier in C # has two effects:

  • Inserts the barriers needed for the target processor.
  • Prevents certain compiler optimizations

In x86 / amd64, (1) does not matter. These processors do not require fences for volatile semantics. (ia64 is different, however.)

So, we get to (2). But, for example, I tried, volatile doesn't make any difference to the jit-ted build.

My question is: can you give an example C # code example where adding a “volatile” modifier to a field leads to another jit-ted assembler?

+6
synchronization c # concurrency volatile
source share
2 answers

Perhaps this one is what you are looking for.

+2
source share

Mark Gravell has a repeatable example of how the absence of the volatile keyword can cause problems.

It was also discussed here.

It is worth noting (as Marc does) that compiler optimization is only visible when compiling in Release mode.

+1
source share

All Articles