Volatile is a hint to the compiler (and the ngen / jit compiler) that the value of this variable can change at any time, and thus optimization around accessing the variable by caching the value locally volatile will be disabled.
Consider the following code:
If (UserName == "") // do something If (UserName == "Fred") // do something
If volatile was not present, the compiler can generate an IL, where it stores the link on the stack for the first comparison and repeats it for the second. However, adding volatile tells the compiler that the link can be changed by another thread, causing it to generate an IL that will not reuse a copy of the stack from the first comparison.
Franci Penov Nov 05 '10 at 3:54
source share