浅谈Pool对象

Pool对象的技术指标:

避免频繁创建经常使用的稀有资源,提高工作效率.

控制阀值,很多情况下一些关键资源都有一个最佳并发数,超过这个拐点性能有可能急剧下降,也有可能继续增大并发数性能不能提升.

安全的获取对象和释放对象(使用之后放回连接池)

public sealed class Pool<T> : IDisposable where T : IDisposable
    {
        private bool disposed = false;
        private Semaphore gate;
        private Stack<T> pool;
        public event Predicate<T> Predicate;
        public Pool(int concrrent,Func<Pool<T>,T> activator)
        {
            if (concrrent <= 0)
            {
                throw new ArgumentException("concrrent");
            }
            if (activator==null)
            {
                throw new ArgumentNullException("activator");
            }
            gate = new Semaphore(concrrent, concrrent);
            pool = new Stack<T>();
            for (int i=0;i< concrrent; i++)
            {
                pool.Push(activator(this)); 
            }
            
        }

        public T Acquire()
        {
            if (!gate.WaitOne())
                throw new InvalidOperationException();
            lock (pool)
            {
                return pool.Pop();
            }
        }

        public void Release(T target)
        {
            lock (pool)
            {
                if (Predicate!=null)
                {
                    if (Predicate(target))
                    {
                        pool.Push(target);
                        gate.Release();
                    }
                }
                else
                {
                    if (target != null)
                    {
                        pool.Push(target);
                        gate.Release();
                    }      
                }
            }
        }

        private void Dispose(bool disposing)
        {
            if (disposed)
                return;
            if (disposing)
            {
                gate.Dispose();
            }
            for (int i = 0; i < pool.Count; i++)
            {
                var t = pool.Pop();
                t.Dispose();
            }
            disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~Pool()
        {
            Dispose(false);
        }
    }

T对象实现时最好与Pool对象建立某种关联,调用T对象实例的某个方法时可以将对象送回Pool,而不是销毁它.同时Pool对象Release对象时,最好通过事件(关联关系)判断是否是从Pool对象获取的,然后放回Pool.

原文地址:https://www.cnblogs.com/kingge/p/5558061.html