const and volatile
The
const
modifier is used to declare fields or local variables that cannot be changed. These
variables must be given initial values when they are declared. Thus, a
const
variable is
essentially a constant. For example,
const int i = 10;
creates a
const
variable called
i
that has the value 10. Although a
const
field is similar to a
readonly
field, the two are not the same. A
const
field cannot be set within a constructor,
but a
readonly
field can.
The
volatile
modifier tells the compiler that a field’s value may be changed by two or
more concurrently executing threads. In this situation, one thread may not know when the
field has been changed by another thread. This is important because the C# compiler will
automatically perform certain optimizations that work only when a field is accessed by a
single thread of execution. To prevent these optimizations from being applied to a shared
field, declare it
volatile
. This tells the compiler that it must obtain the value of this field each
time it is accessed.
Do'stlaringiz bilan baham: |