using System; using System.Collections.Generic; namespace AX.Common { public class ObjectPool { private Queue queue; private Func creator; private Action clearer; public int AvailableCount { get { return this.queue.Count; } } public ObjectPool(int initialCount, Func creator, Action clearer = null) { if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount"); if (creator == null) throw new ArgumentNullException("creator"); this.queue = new Queue(initialCount); this.creator = creator; this.clearer = clearer; } /// /// 从对象池获得一个对象实例。 /// public T Acquire() { if (queue.Count != 0) return queue.Dequeue(); return creator(); } /// /// 把指定的对象实例归还对象池。 /// public void Release(T obj) { if (clearer != null) clearer(obj); queue.Enqueue(obj); } public void Clear() { if (typeof(T) == typeof(IDisposable)) { while (queue.Count != 0) { var obj = queue.Dequeue(); ((IDisposable)obj).Dispose(); } } else { queue.Clear(); } queue.TrimExcess(); } } }