日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

浅谈Pool对象

發布時間:2024/4/24 42 生活家
生活随笔 收集整理的這篇文章主要介紹了 浅谈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.

總結

以上是生活随笔為你收集整理的浅谈Pool对象的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。