Volatile (computer programming): Difference between revisions

Content deleted Content added
m In C#: + exclusions
Line 226:
==In C#==
 
In [[C Sharp (programming language)|C#]], <code>volatile</code> ensures that code accessing the field is not subject to some thread-unsafe optimizations that may be performed by the compiler, the CLR, or by hardware. Only the following types can be marked volatile: all reference types, Single, Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Char, and all enumerated types with an underlying type of Byte, SByte, Int16, UInt16, Int32, or UInt32.<ref>{{cite book |last1=Richter |first1=Jeffrey |title=CLR Via C# |publisher=Microsoft Press |date=February 11, 2010 |pages=183 |chapter=Chapter 7: Constants and Fields |isbn=0-7356-2704-5}}</ref> (This excludes value [[struct]]s, as well as the primitive types longer than 32 bits such as Double, Int64, UInt64 and UInt64Decimal.)
 
Basically <code>volatile</code> is a shorthand for calling <code>Thread.VolatileRead</code> and <code>Thread.VolatileWrite</code>. These methods are special. In effect, these methods disable some optimizations usually performed by the C# compiler, the JIT compiler, and the CPU itself. The methods work as follows:<ref>{{cite book |last1=Richter |first1=Jeffrey |title=CLR Via C# |publisher=Microsoft Press |date=February 11, 2010 |pages=797–803 |chapter=Chapter 28: Primitive Thread Synchronization Constructs |isbn=0-7356-2704-5}}</ref>