All pastes #720949 Raw Edit

Unnamed

public text v1 · immutable
#720949 ·published 2007-09-30 20:33 UTC
rendered paste body
/// <summary>
    /// Syncronized List{T} based on SynchronizedDictionary provided by Nomad
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SyncronizedList<T> : List<T>
    {
        private readonly ReaderWriterLockSlim m_rwLock = new ReaderWriterLockSlim();
        private volatile int m_userLock = 0;

        public SyncronizedList() : base() { }
        public SyncronizedList(int capacity) : base(capacity) { }
        public SyncronizedList(IEnumerable<T> collection) : base(collection) { }

        public new T this[int index]
        {
            get
            {
                if (index > Count)
                    throw new ArgumentOutOfRangeException("index");

                if (m_rwLock != 0 && m_userLock == Thread.CurrentThread.ManagedThreadId)
                {
                    return base[index];
                }

                T result;
                try
                {
                    m_rwLock.EnterReadLock();
                    result = base[index];
                }
                finally
                {
                    m_rwLock.ExitReadLock();
                }

                return result;
            }
            set
            {
                if (index > Count)
                    throw new ArgumentOutOfRangeException("index");

                if (m_userLock != 0 && m_userLock == Thread.CurrentThread.ManagedThreadId)
                {
                    base[key] = value;
                    return;
                }                               

                try
                {
                    m_rwLock.EnterWriteLock();
                    base[index] = value;
                }
                finally
                {
                    m_rwLock.ExitWriteLock();
                }
            }
        }

        public new void Add(T value)
        {
            if (m_userLock != 0 && m_userLock == Thread.CurrentThread.ManagedThreadId)
            {
                base.Add(value);
                return;
            }

            try
            {
                m_rwLock.EnterWriteLock();
                base.Add(value);
            }
            finally
            {
                m_rwLock.ExitWriteLock();
            }
        }


        public void ReadLock()
        {
            m_rwLock.EnterReadLock();
            m_userLock = Thread.CurrentThread.ManagedThreadId;
        }

        public void ReadUnlock()
        {
            m_userLock = 0;
            m_rwLock.ExitReadLock();
        }
    }