/// <summary> /// 回收对象,无法回收由外部创建的对象 /// </summary> /// <param name="obj">对象实例</param> public void RecycleObject(T obj) { if (obj == null || !_UsedPool.Contains(obj)) { return; } _UsedPool.Remove(obj); _Pool.Enqueue(obj); }
/// <summary> /// 构造函数 /// </summary> /// <param name="poolSize">池子最大容量</param> /// <param name="fill">初始化时是否填满池子</param> /// <param name="template">克隆模板(模板不为空时将自动调用CloneTools.DeepCopy进行拷贝)</param> public ObjectPool(int poolSize, bool fill = false, T template = null) { _Template = template; _Pool = new RingQueue <T>(poolSize); if (fill) { if (template == null) { for (int i = 0; i < poolSize; i++) { _Pool.Enqueue(new T()); } } else { for (int i = 0; i < poolSize; i++) { _Pool.Enqueue(CloneTools.DeepCopy(template)); } } } _UsedPool = new List <T>(_Pool.RingSize); }
static void TestRingQueue() { Console.Title = "环队列测试"; RingQueue <int> queue = new RingQueue <int>(10); queue.Enqueue(666); queue.Enqueue(777); var n = queue.Peek(); var n1 = queue.Dequeue(); Console.WriteLine(n); Console.WriteLine(n1); for (int i = 0; i < 15; i++) { queue.Enqueue(i); } foreach (var temp in queue) { Console.WriteLine(temp); } Console.WriteLine("======================="); while (!queue.IsEmpty) { Console.WriteLine(queue.Dequeue()); } Console.WriteLine("======================="); Console.WriteLine("10000000次入队出队:"); RingQueue <int> queue1 = new RingQueue <int>(10001); Queue <int> queue2 = new Queue <int>(); int max = 10000000; Random random = new Random(); Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { queue2.Enqueue(random.Next()); } while (queue2.Count > 0) { queue2.Dequeue(); } stopwatch.Stop(); Console.WriteLine("原队列:{0}", stopwatch.Elapsed); stopwatch.Restart(); for (int i = 0; i < max; i++) { queue1.Enqueue(random.Next()); } while (!queue1.IsEmpty) { queue1.Dequeue(); } stopwatch.Stop(); Console.WriteLine("环队列:{0}", stopwatch.Elapsed); }