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.
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;
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
Multithreaded applications are a must today.The Dot Net Framework makes creating these applications much easier than traditional programming methods. Be sure to take advantage of multithreading and of all available methods of synchronization.
When designing for multithreaded applications remember the age-old proverb: An ounce of prevention is worth a pound of cure. It is much easier to prevent deadlocks and other multithreaded bugs by taking a few extra minutes and trying to prevent them. You will usually spend a lot of time trying to find the cause of these bugs when reported from the field, as they don’t usually show up stepping through code, but only when running at full speed.