I can\'t find any example of VolatileRead/write (try...) but still:
When should I use volatile
vs VolatileRead
?
When you need more fine grained control over the way fences are applied to the code can you can use the static
Thread.VolatileRead or Thread.VolatileWrite .
Declaring a variable volatile means that the compiler doesn't cache it's value and always reads the field value, and when a write is performed the compiler writes assigned values immediately.
The two methods Thread.VolatileRead and Thread.VolatileWrite gives you the ability to have a finer grained control without declaring the variable as volatile, since you can decide when perform a volatile read operation and when a volatile write, without having the bound to read no cached and write immediately that you have when you declare the variale volatile, so in poor words you have more control and more freedom ...
VolatileRead()
reads the latest version of a memory address, and VolatileWrite()
writes to the address, making the address available to all threads. Using both VolatileRead()
and VolatileWrite()
consistently on a variable has the same effect as marking it as volatile.
Take a look at this blog post that explains by example the difference ...
Why the line int num = address; is there ? they already have the address argument which is clearly holding the value.
It is a defensive copy to avoid that something outside change the value while we are inside the method, the integer value is copied to the local variable to avoid an accidental change from outside.
Since in Visual Basic the volatile keyword doesn't exist you have the only choice of using consistently VolatileRead()
and VolatileWrite()
static methods to achieve the same effect of the volatile keyword in c#.