title: c# - Volatile keyword usage vs lock
body: <p>I've used volatile where I'm not sure it is necessary. I was pretty sure a lock would be overkill in my situation. Reading this thread (Eric Lippert comment) make me anxious on my usage of volatile: <a href="https://stackoverflow.com/questions/72275/when-should-the-volatile-keyword-be-used-in-c/72453#72453">When should the volatile keyword be used in c# ?</a></p>
  
  <p>I used volatile because my variable is use in a Multithreaded context where this variable could be accessed/modified concurrently, but where I can loose an addition without any hurts (see code).</p>
  
  <p>I added "volatile" to make sure that there is no miss alignment occurring: reading only 32 bits of the variable and the other 32 bits on another fetch which can be broken in 2 by a write in the middle from another thread.</p>
  
  <p>Does my previous assumption (previous statement) can really happen of not ? If not, does "volatile" usage is still necessary (Option properties modifications could happen in any thread).</p>
  
  <blockquote>
    <p>After reading the 2 first answers. I would like to insists on the fact that the way the code is written, it is not important if due to concurrency we miss an increment (want to increment from 2 threads but the result is only incremented by one due to concurrency) if at least the variable '_actualVersion' is incremented.</p>
  </blockquote>
  
  <p>As reference, this is the part of code where I'm using it. It is to report save action (write to disk) only while the application is idle.</p>
  
  <pre><code>public abstract class OptionsBase : NotifyPropertyChangedBase
  {
      private string _path;
  
      volatile private int _savedVersion = 0;
      volatile private int _actualVersion = 0;
  
      // ******************************************************************
      void OptionsBase_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
      {
          _actualVersion++;
          Application.Current.Dispatcher.BeginInvoke(new Action(InternalSave), DispatcherPriority.ApplicationIdle);
      }
  
      // ******************************************************************
      private void InternalSave()
      {
          if (_actualVersion != _savedVersion)
          {
              _savedVersion = _actualVersion;
              Save();
          }
      }
  
      // ******************************************************************
      /// &lt;summary&gt;
      /// Save Options
      /// &lt;/summary&gt;
      private void Save()
      {
          using (XmlTextWriter writer = new XmlTextWriter(_path, null))
          {
              writer.Formatting = Formatting.Indented;
              XmlSerializer x = new XmlSerializer(this.GetType());
  
              x.Serialize(writer, this);
              writer.Close();
          }
      }
  </code></pre>