I’m familiar with the basic idea of volatile (to prevent compiler optimization of instructions involving values that may be accessed from multiple threads, in summary), but I’ve noticed that examples I’ve found involving volatile and .NET 3.5 collections (NOT .NET 4 Concurrent collections. I know what they are but my current context does not allow me to use .NET 4.) never have volatile applied to the collection itself. Of course the collection (or a corresponding locking object) will need to be locked when accessing it from multiple threads, but is there a reason that a collection should not be marked volatile? Is the type of collection significant (i.e. a List of value types versus a List of reference types)?
I’m familiar with the basic idea of volatile (to prevent compiler optimization of instructions
Share
Volatile almost certainly doesn’t mean what you think it does. That’s the main reason for not using it. (These days I refuse to try to describe what volatile means. It’s too complicated to explain neatly, and it’s almost always the wrong approach unless you’re a memory model expert, in which case you definitely don’t need me to explain it to you.)
If you’re locking on an appropriate object, what benefit do you believe it will give you? You’re already going to be going through appropriate memory fences in acquiring and releasing the lock… I suspect any reasons for using
volatilefor the variable itself are based on a misunderstanding.