How would you simplify Entering and Exiting a ReaderWriterLock?

前端 未结 5 725

This seems very noisy to me. Five lines of overhead is just too much.

m_Lock.EnterReadLock()
Try
    Return m_List.Count
Finally
    m_Lock.ExitReadLock()
En         


        
5条回答
  •  星月不相逢
    2020-12-14 12:18

    This is not my invention but it certainly has made by hair a little less gray.

    internal static class ReaderWriteLockExtensions
    {
        private struct Disposable : IDisposable
        {
            private readonly Action m_action;
            private Sentinel m_sentinel;
    
            public Disposable(Action action)
            {
                m_action = action;
                m_sentinel = new Sentinel();
            }
    
            public void Dispose()
            {
                m_action();
                GC.SuppressFinalize(m_sentinel);
            }
        }
    
        private class Sentinel
        {
            ~Sentinel()
            {
                throw new InvalidOperationException("Lock not properly disposed.");
            }
        }
    
        public static IDisposable AcquireReadLock(this ReaderWriterLockSlim lock)
        {
            lock.EnterReadLock();
            return new Disposable(lock.ExitReadLock);
        }
    
        public static IDisposable AcquireUpgradableReadLock(this ReaderWriterLockSlim lock)
        {
            lock.EnterUpgradeableReadLock();
            return new Disposable(lock.ExitUpgradeableReadLock);
        }
    
        public static IDisposable AcquireWriteLock(this ReaderWriterLockSlim lock)
        {
            lock.EnterWriteLock();
            return new Disposable(lock.ExitWriteLock);
        }
    } 
    

    How to use:

    using (m_lock.AcquireReadLock())
    {
        // Do stuff
    }
    

提交回复
热议问题