Check out my new blog at

Wednesday, May 14, 2008

C# - Volatility and the Volatile Keyword

I am doing impact analysis regarding changes I need to make on a code base pretty late in the development cycle.    I came across an older piece of code I wrote that uses the C# volatile keyword.  It got me thinking about how and why I was using volatile to the point where I became unsure of my original implementation (that's always scary at the end of a development cycle).  I started to read up on volatile...

First, read MSDN's description here:

Then read MSDN's .NET Framework 3.5 treatment on the topic here:

Read the about a thread termination scheme using volatile here:

This statement is important:

"The use of volatile with the _shouldStop data member enables you to safely access this member from multiple threads without the use of formal thread synchronization techniques, but only because _shouldStop is a bool. This means that only single, atomic operations are necessary to modify _shouldStop. If, however, this data member were a class, struct, or array, accessing it from multiple threads would likely cause intermittent data corruption..."


Okay, that makes great sense but what is happening underneath the .NET covers?    Why use volatile instead of a lock?  Is volatile just a convenience for serializing accesses to simple data types or does it mean something more?   Are there better or more efficient constructs to use over volatile?

For answers, I read the following:

My conclusion: while my use of volatile does what I intended it to, I will use locks or some sort of signaling mechanism from this point forward.

No comments :


Content on this site is provided "AS IS" with no warranties and confers no rights. Additionally, all content on this site is my own personal opinion and does not represent my employer's view in any way.