Let\'s say that a class has a public int counter
field that is accessed by multiple threads. This int
is only incremented or decremented.
T
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:
sbyte
, byte
, short
, ushort
, int
, uint
, char
, float
, and bool
.byte
, sbyte
, short
, ushort, int
, or uint
.IntPtr
and UIntPtr
.Other types, including double
and long
, cannot be marked "volatile"
because reads and writes to fields of those types cannot be guaranteed
to be atomic. To protect multi-threaded access to those types of
fields, use the Interlocked
class members or protect access using the
lock
statement.