#region License /* Copyright (c) 2010-2014 Danko Kozar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion License using System.Collections.Generic; namespace eDriven.Core.Util { /// /// The generic object pool /// Used for making the objects reusable /// This is the efficient anti-measure for memory leaks /// /// Coded by Danko Kozar /// public class ObjectPool where T : new() { private readonly Queue _queue = new Queue(); private int _poolSize = 1000; /// /// The maximum number of objects that this pool can hold /// public int PoolSize { get { return _poolSize; } set { _poolSize = value; // TODO: A case when pool size is changed dinamically when holding objects //if (_queue.Count > _poolSize) {} } } #region Constructors /// /// Constructor for a pool with default size /// public ObjectPool() { } /// /// Constructor /// /// Pool size public ObjectPool(int poolSize) { _poolSize = poolSize; } #endregion /// /// Adds an object to the pool /// /// Object to be added public void Put(T obj) { if (_queue.Count >= PoolSize) return; _queue.Enqueue(obj); } /// /// Puts a list of objects into the pool /// /// Objects to be added public void Put(List objects) { objects.ForEach(delegate (T o) { if (_queue.Count >= PoolSize) return; _queue.Enqueue(o); }); } /// /// Releases an object from the pool /// /// The object from the pool, or a new created one if a pool is empty public T Get() { if (_queue.Count != 0) { return _queue.Dequeue(); } return new T(); } /// /// Returns the current count /// public int Count { get { return _queue.Count; } } public override string ToString() { return string.Format(@"ObjectPool<{0}> [Holding: {1}/{2}]", typeof(T), _queue.Count, PoolSize); } } }