clr/c++自定线程安全集合

代码如下:

难点重写索引器、重写基类方法、基类方法显示调用示例

generic <class T> public ref class SyncList : public List<T>
    {
    private:
        Object^ _rootLock = gcnew Object();

    public:
        virtual property T default[int]
        {
            T get(int index) new
            {
                try
                {
                    Monitor::Enter(_rootLock);
                    return List::default[index];
                }
                finally
                {
                    Monitor::Exit(_rootLock);
                }
             }
             void set(int index,T value) new
             {
                 try
                 {
                    Monitor::Enter(_rootLock);
                    List::default[index] = value;
                 }
                 finally
                 {
                    Monitor::Exit(_rootLock);
                 }
             }
        }

    public:
        virtual void Add(T item)new
        {
            try
            {
                Monitor::Enter(_rootLock);
                List::Add(item);
            }
            finally
            {
               Monitor::Exit(_rootLock);
            }
        }

        virtual void AddRange(IEnumerable<T>^ items)new
        {
            try
            {
                Monitor::Enter(_rootLock);
                List::AddRange(items);
            }
            finally
            {
               Monitor::Exit(_rootLock);
            }
        }

        virtual void Remove(T item)new
        {
            try
            {
                Monitor::Enter(_rootLock);
                List::Remove(item);
            }
            finally
            {
               Monitor::Exit(_rootLock);
            }
        }

        virtual void RemoveAt(int index)new
        {
            try
            {
                Monitor::Enter(_rootLock);
                List::RemoveAt(index);
            }
            finally
            {
               Monitor::Exit(_rootLock);
            }
        }
    };
原文地址:https://www.cnblogs.com/guanglin/p/11188360.html