A wish: Execute under Lock method in sync objects

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • valentin tihomirov

    #1

    A wish: Execute under Lock method in sync objects

    It is quite convenient to use the basic primitive:

    lock(object) {
    method();
    }

    On the other hand,

    rwLock.AcquireR eaderLock(-1);
    try { // unlock finally
    method();
    } finally {
    rwLock.ReleaseR eaderLock();
    }

    is much less cosy but is typical scenario, I beleive. I would prefer:

    rwLock.RLock(-1) {
    method();
    }

    instead. Why not to introduce the utility methods?


  • Jon Skeet [C# MVP]

    #2
    Re: A wish: Execute under Lock method in sync objects

    On Nov 15, 12:49 pm, "valentin tihomirov" <V_tihomi...@be st.eewrote:
    It is quite convenient to use the basic primitive:
    >
    lock(object) {
    method();
    >
    }
    >
    On the other hand,
    >
    rwLock.AcquireR eaderLock(-1);
    try { // unlock finally
    method();
    } finally {
    rwLock.ReleaseR eaderLock();
    }
    >
    is much less cosy but is typical scenario, I beleive. I would prefer:
    >
    rwLock.RLock(-1) {
    method();
    }
    >
    instead. Why not to introduce the utility methods?
    You wouldn't really even need that - just make the AcquireReaderLo ck
    method return a Disposable; then you can do:

    using (rwLock.Acquire ReaderLock())
    {
    method();
    }

    That's the approach I take with my own lock wrapper:


    Jon

    Comment

    • Chris Mullins [MVP - C#]

      #3
      Re: A wish: Execute under Lock method in sync objects

      It's really pretty easy, and I do it all the time. Much like Jon's Padlock
      class, I use something that looks like this:

      public class ReadLock : IDisposable
      {
      private readonly ReaderWriterLoc k _rwlock;
      public ReadLock(Reader WriteLock rw)
      {
      _rwlock = rw;
      _rwLock.Acquire ReadLock(...);
      }

      public void Dispose()
      {
      _rwLock.ExitRea dLock();
      }
      }

      --
      Chris Mullins

      "valentin tihomirov" <V_tihomirov@be st.eewrote in message
      news:%23impYX4J IHA.5624@TK2MSF TNGP04.phx.gbl. ..
      It is quite convenient to use the basic primitive:
      >
      lock(object) {
      method();
      }
      >
      On the other hand,
      >
      rwLock.AcquireR eaderLock(-1);
      try { // unlock finally
      method();
      } finally {
      rwLock.ReleaseR eaderLock();
      }
      >
      is much less cosy but is typical scenario, I beleive. I would prefer:
      >
      rwLock.RLock(-1) {
      method();
      }
      >
      instead. Why not to introduce the utility methods?
      >

      Comment

      Working...