I would like to add to mentioned in the other answers the difference between volatile
, Interlocked
, and lock
:
The volatile keyword can be applied to fields of these types:
- Reference types.
- Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In otherwords, you cannot declare a "pointer" to be "volatile".
- Simple types such as
sbyte
,byte
,short
,ushort
,int
,uint
,char
,float
, andbool
. - An enum type with one of the following base types:
byte
,sbyte
,short
, ushort,int
, oruint
. - Generic type parameters known to be reference types.
IntPtr
andUIntPtr
.
Other types, including double
and long
, cannot be marked "volatile"because reads and writes to fields of those types cannot be guaranteedto be atomic. To protect multi-threaded access to those types offields, use the Interlocked
class members or protect access using thelock
statement.