title: 'using' statement vs 'try finally'
body: <p>I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a <code>try finally</code> or a <code>using</code> clause.</p>
  
  <p>In the <code>try finally</code> I would acquire the lock before the <code>try</code>, and release in the <code>finally</code>. In the <code>using</code> clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.</p>
  
  <p>I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than <code>try finally</code>. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.</p>
  
  <p>Method 1 (<code>try finally</code>):</p>
  
  <pre><code>static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock();
  private DateTime dtMyDateTime_m
  public DateTime MyDateTime
  {
      get
      {
          rwlMyLock_m .AcquireReaderLock(0);
          try
          {
              return dtMyDateTime_m
          }
          finally
          {
              rwlMyLock_m .ReleaseReaderLock();
          }
      }
      set
      {
          rwlMyLock_m .AcquireWriterLock(0);
          try
          {
              dtMyDateTime_m = value;
          }
          finally
          {
              rwlMyLock_m .ReleaseWriterLock();
          }
      }
  }
  </code></pre>
  
  <p>Method 2:</p>
  
  <pre><code>static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock();
  private DateTime dtMyDateTime_m
  public DateTime MyDateTime
  {
      get
      {
          using (new ReadLock(rwlMyLock_m))
          {
              return dtMyDateTime_m;
          }
      }
      set
      {
          using (new WriteLock(rwlMyLock_m))
          {
              dtMyDateTime_m = value;
          }
      }
  }
  
  public class ReadLock : IDisposable
  {
      private ReaderWriterLock rwl;
      public ReadLock(ReaderWriterLock rwl)
      {
          this.rwl = rwl;
          rwl.AcquireReaderLock(0);
      }
  
      public void Dispose()
      {
          rwl.ReleaseReaderLock();
      }
  }
  
  public class WriteLock : IDisposable
  {
      private ReaderWriterLock rwl;
      public WriteLock(ReaderWriterLock rwl)
      {
          this.rwl = rwl;
          rwl.AcquireWriterLock(0);
      }
  
      public void Dispose()
      {
          rwl.ReleaseWriterLock();
      }
  }
  </code></pre>