Well using the "volatile" keyword tells how to handle read the write
operations of such variables. For most of the variables the C# compiler caches
the value of the object in the register and it may reuse this same value for
further operations (esp if u r using threads). Using the volatile keyword
ensures that the current value of the object is read every time.
Volatile keyword is particulary useful when an external process or thread
can change the value of the variable and you need to ensure that you get the
changed or the latest value every time.
It is even know that sometimes the compiler also allows the thread to keep
the local comy of certain shared variables thus increasing its effeciency. So
when such shared variables are declared as volatile the value of these variables
are not placed in the registers but infact the C# compiler and JIT ensures that
these variables are created in the global memory.
Declaring the variable volatile also ensures that the threads which read
and write to these variables are always in the same order and they are not
reordered. Thus in C# the volatile prevents such problems from occurring because
reads and writes cannot be reordered.
As for the type of variable only below types are supported as "volatile" by
the C# complier :
- Any reference type.
- Any pointer type (in an unsafe context).
- Datatypes like sbyte, byte, short, ushort, int, uint, char, float, bool.
- An enum type with an enum base type of byte, sbyte, short, ushort, int, or
uint.
-- Please post your queries and comments for my
articles in the usergroup for the benefit of all. I hope this step from my end
is helpful to all of us.
Regards,
Namratha
(Nasha) |