Why readonly and volatile modifiers are mutually exclusive? Why readonly and volatile modifiers are mutually exclusive? multithreading multithreading

Why readonly and volatile modifiers are mutually exclusive?


Neither the readonly nor volatile modifiers are penetrative. They apply to the reference itself, not the object's properties.

The readonly keyword asserts—and enforces—that a variable cannot change after initialization. The variable is the small chunk of memory where the reference is stored.

The volatile keyword tells the compiler that the contents of a variable might be changed by multiple threads. This prevents the compiler from using optimizations (such as reading the variable's value into a register and using that value over several instructions) that might cause problems with concurrent access. Again, this only affects the small chunk of memory where the reference is stored.

Applied this way, you can see that they are indeed mutually exclusive. If something is readonly (can only be written to once, at initialization or construction), then it can't also be volatile (can be written to at any time by multiple threads).


As for your concern about caching issues, IIRC, there are pretty strict rules about when the compiler can cache the result of a property call. Keep in mind that it is a method call, and it's a pretty heavy optimization (from the compiler's stand-point) to cache its value and skip calling it again. I don't think it's something you need to concern yourself with overly much.


A readonly field can only be written when the object is first constructed. Therefore there won't be any caching issue on the CPU because the field is immutable and can't possibly change.


While the reference itself might be thread-safe, its properties might not. Think about what would happen if two threads tried to simultaneously iterate through a List contained within your reference object.