Multithreading in VB.NET

Volatile Keyword & Conclusion

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.

Summary

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.

You might also like...

Comments

About the author

John Spano United States

John Spano cofounder and CTO of NeoTekSystems, a Greenville, South Carolina technology consulting company. NeoTekSystems offers IT consulting, custom programming, web design and web hosting. We ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match” - Bill Bryson