Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Multithreading in VB.NET  »  A Quick Word on the volatile Keyword
Multithreading in VB.NET
by John Spano | Published  07/16/2005 | .NET Framework | Rating:
A Quick Word on the volatile Keyword

A Quick Word on the volatile Keyword

 

    In your reading or study of .Net code, the volatile C# keyword might come up.  This keyword does not exist in Visual Basic.  Don’t worry though; it doesn’t add any functionality to C# that can’t be done with the other synchronization objects discussed in this case study.

    The volatile keyword tells the compiler that the variable it references could change at anytime and that no optimizations should be done to it.  It will prohibit the compiler from storing the variable in a register and force it read it new from memory each time.

    Variables marked as volatile aren’t necessarily thread safe.  They only insure that each read of the variable is the latest information.  To see what a declaration looks like look at the following code snip-it, which declares an Integer variable as volatile.

private volatile int MyInteger;

    Use of Monitor is a much safer and better way to handle synchronization.  It guarantees that the variable is up to date as only one thread is accessing the variable at a time.  It is safe to replace volatile variable access with Monitor blocks of code or any other synchronization method discussed in the case study that fit your needs.  Good synchronization practice will eliminate the need for volatile.

Sponsored Links