private bool Expired(ResourcePoolItem <T> item) { if (item.Static || _maxItemUses < 0) { return(false); } return(item.TimesUsed >= _maxItemUses); }
/// <summary> /// Creates <paramref name="minimumItemCount"/> idle static items. /// </summary> /// <param name="minimumItemCount">The number of items to create</param> protected void InitializeStaticItems(short minimumItemCount) { ResourcePoolItem <T> item; poolLock.Write(() => { for (int i = 0; i < minimumItemCount; i++) { item = new ResourcePoolItem <T>(_buildItemDelegate(), this); item.Static = true; item.Idle = true; item.NextItem = nextItem; nextItem = item; IncrementAllocatedItems(); } }); }
/// <summary> /// Release the item for reuse. If the resetItemDelegate was set, it will be called before the item is reused. /// </summary> /// <param name="item">The item to release.</param> /// <remarks>It is recommended that this be called in a finally block after a try block which uses the item.</remarks> public void ReleaseItem(ResourcePoolItem <T> item) { if (item == null) { throw new ArgumentNullException("item"); } DecrementItemsInUse(); if (!item.Idle) { if (!Expired(item)) { item.TimesUsed++; if (_resetItemDelegate != null) { _resetItemDelegate(item.Item); } poolLock.Write(() => { if (nextItem == null) { nextItem = item; } else { ResourcePoolItem <T> newNextItem = item; ResourcePoolItem <T> currentNextItem = nextItem; newNextItem.NextItem = currentNextItem; nextItem = newNextItem; } item.Idle = true; }); } else { item.Dispose(); } } }
/// <summary> /// Gets an item from the pool. If no items are available, a new one will be created. /// </summary> /// <returns>A ResourcePoolItem from this pool.</returns> /// <remarks>You must call ReleaseItem on the Item when you are done with it. It is recommended to use a finally block to do so.</remarks> public ResourcePoolItem <T> GetItem() { ResourcePoolItem <T> item = null; poolLock.Write(() => { if (nextItem != null) { item = nextItem; nextItem = item.NextItem; item.NextItem = null; item.Idle = false; IncrementItemsInUse(); } }); if (item != null) { return(item); } item = new ResourcePoolItem <T>(_buildItemDelegate(), this); IncrementAllocatedItems(); IncrementItemsInUse(); return(item); }