title: Thread Safe Properties in C#
body: <p>I am trying to create thread safe properties in C# and I want to make sure that I am on the correct path - here is what I have done -</p>
  
  <pre><code>private readonly object AvgBuyPriceLocker = new object();
  private double _AvgBuyPrice;
  private double AvgBuyPrice 
  {
      get
      {
          lock (AvgBuyPriceLocker)
          {
              return _AvgBuyPrice;
          }
      }
      set
      {
          lock (AvgBuyPriceLocker)
          {
              _AvgBuyPrice = value;
          }
      }
  }
  </code></pre>
  
  <p>Reading this posting, it would seem as if this isn't the correct way of doing it -</p>
  
  <p><a href="https://stackoverflow.com/questions/505515/c-thread-safety-with-get-set">C# thread safety with get/set</a></p>
  
  <p>however, this article seems to suggest otherwise,</p>
  
  <p><a href="http://www.codeproject.com/KB/cs/Synchronized.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/Synchronized.aspx</a></p>
  
  <p>Does anybody have a more definitive answer?</p>
  
  <p>Edit:</p>
  
  <p>The reason that I want to do the Getter/Setter for this property is b/c I actually want it to fire an event when it is set - so the code would actually be like this -</p>
  
  <pre><code>public class PLTracker
  {
  
      public PLEvents Events;
  
      private readonly object AvgBuyPriceLocker = new object();
      private double _AvgBuyPrice;
      private double AvgBuyPrice 
      {
          get
          {
              lock (AvgBuyPriceLocker)
              {
                  return _AvgBuyPrice;
              }
          }
          set
          {
              lock (AvgBuyPriceLocker)
              {
                  Events.AvgBuyPriceUpdate(value);
                  _AvgBuyPrice = value;
              }
          }
      }
  }
  
  public class PLEvents
  {
      public delegate void PLUpdateHandler(double Update);
      public event PLUpdateHandler AvgBuyPriceUpdateListener;
  
      public void AvgBuyPriceUpdate(double AvgBuyPrice)
      {
          lock (this)
          {
              try
              {
                  if (AvgBuyPriceUpdateListener!= null)
                  {
                      AvgBuyPriceUpdateListener(AvgBuyPrice);
                  }
                  else
                  {
                      throw new Exception("AvgBuyPriceUpdateListener is null");
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex.Message);
              }
          }
      }
  }
  </code></pre>
  
  <p>I am pretty new to making my code thread safe so please feel free to tell me if I am going about it in the totally wrong way!</p>
  
  <p>Will</p>