title: Can I use C# lock operator inside the property to synchronize access to read/write to a variable?
body: <p>I presently write C# WPF application. I'm in need of synchronous access for read/write to a variable from three threads. This variable is declared as the member of the application main window class. So I declared it in the following way:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      . . . . .
      #region Fields
      /// &lt;summary&gt;
      /// The variable myVar to synchronous access for read/write. 
      /// &lt;/summary&gt;
      private static Double myVar;
      #endregion
      . . . . .
  }
  </code></pre>
  
  <p>Can I provide the synchronous access to it in the following way:</p>
  
  <p>1) Define the synchronization object as the member of MainWindow class</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      . . . . .
      #region Fields
      /// &lt;summary&gt;
      /// This object is controlling the synchronous access for read/write to myVar. 
      /// &lt;/summary&gt;
      private static Object syncObj;
      #endregion
      . . . . .
  }
  </code></pre>
  
  <p>2) Define the next property in the MainWindow class</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      . . . . .
      #region Properties
      /// &lt;summary&gt;
      /// This property supports synchronous access to myVar for read/write. 
      /// &lt;/summary&gt;
      public static Double MyVar
      {
          lock(syncObj)
          {
              get{ return myVar; }
              set{ if(myVar != value) myVar = value; }
          }
      } 
      #endregion
      . . . . .
  }
  </code></pre>
  
  <p>Will this property work in the right way? Will it ensure sure method of synchronous access for read/write to myVar variable? I don't want to use volatile or methods as Thread.VolatileRead and Thread.VolatileWrite because many people say that lock operator works better and allow to compiler to optimize code.</p>