private void Return(IPoolable poolable) { var poolable1 = (T)poolable; _freeItems.AddToBack(poolable1); _usedItems.Remove(poolable1); }
/// <summary> /// Get a free element from the <see cref="Pool{T}" />. /// </summary> /// <param name="killExistingObjectIfFull"> /// <c>true</c> to forcibly kill an existing, in use, element in the <see cref="Pool{T}" /> if <see cref="Count" /> is /// equal to <see cref="Capacity" />; otherwise, <c>false</c>. /// </param> /// <returns>A free <see cref="T" /> element from the <see cref="Pool{T}" />.</returns> /// <remarks> /// <para>This method is an O(1) operation.</para> /// </remarks> public T Request(bool killExistingObjectIfFull = false) { while (true) { T poolable; if (_freeItems.RemoveFromFront(out poolable)) { poolable.Initialize(Return); _usedItems.AddToBack(poolable); return(poolable); } if (!killExistingObjectIfFull) { return(null); } if (!_usedItems.GetFront(out poolable)) { return(null); } poolable.Return(); killExistingObjectIfFull = false; } }
public void Free(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (_freeItems.Count < _maximum) { _freeItems.AddToBack(item); } _resetItem(item); }
/// <summary> /// Initializes a new instance of the <see cref="Pool{T}" /> class that has a specified capacity and an element /// instantiating delegate. /// </summary> /// <param name="capacity">The number of elements that the new <see cref="Pool{T}" /> can store.</param> /// <param name="instantiationFunction">The delegate responsible for instantiating elements.</param> public Pool(int capacity, Func <int, T> instantiationFunction) { if (instantiationFunction == null) { throw new ArgumentNullException(nameof(instantiationFunction)); } _instantiationFunction = instantiationFunction; _freeItems = new Deque <T>(capacity); _usedItems = new Deque <T>(capacity); for (var i = 0; i < capacity; i++) { var poolable = CreateObject(i); _freeItems.AddToBack(poolable); } }
private void Return(IPoolable item) { Debug.Assert(item != null); var poolable1 = (T)item; var previousNode = (T)item.PreviousNode; var nextNode = (T)item.NextNode; if (previousNode != null) { previousNode.NextNode = nextNode; } if (nextNode != null) { nextNode.PreviousNode = previousNode; } if (item == _headNode) { _headNode = nextNode; } if (item == _tailNode) { _tailNode = previousNode; } if (_tailNode != null) { _tailNode.NextNode = null; } _freeItems.AddToBack(poolable1); ItemReturned?.Invoke((T)item); }
public void Deque_Add_Back(int count) { var deque = new Deque<TestDequeElement>(); for (var i = 0; i < count; i++) { deque.AddToBack(new TestDequeElement { Value = i }); } Assert.IsTrue(deque.Count == count); Assert.IsTrue(deque.Capacity >= count); for (var index = 0; index < deque.Count; index++) { var element = deque[index]; Assert.IsTrue(element.Value == index); } }