Beispiel #1
0
        private void ReturnRentedObject(RentedObject rentedObject)
        {
#if POOLING
            lock (Sentinel)
            {
                rentedObject.IsRented = false;
                if (rentedObject.Index < MinimumUnrentedIndex)
                {
                    MinimumUnrentedIndex = rentedObject.Index;
                }
            }
#endif
        }
Beispiel #2
0
        /// <summary>
        /// Rents an object from the pool. If the pool has no available objects, it creates
        /// a new object by calling <see cref="ObjectConstructor"/>.
        /// </summary>
        /// <returns>
        /// The rented object which must be disposed of to return it to the pool.
        /// </returns>
        public RentedObject Rent()
        {
#if POOLING
            lock (Sentinel)
            {
                // Loop through entries to find an unrented one.
                while (true)
                {
                    if (MinimumUnrentedIndex == CreatedObjectCount)
                    {
                        if (MinimumUnrentedIndex == PooledObjectCapacity)
                        {
                            // Grow the array.
                            int            newPooledObjectCapacity = PooledObjectCapacity * 2;
                            RentedObject[] newPooledObjects        = new RentedObject[newPooledObjectCapacity];
                            Array.Copy(PooledObjects, newPooledObjects, PooledObjectCapacity);

                            PooledObjectCapacity = newPooledObjectCapacity;
                            PooledObjects        = newPooledObjects;
                        }

                        // Create a new object and store at the current index.
                        TPooledObject newObject      = ObjectConstructor();
                        RentedObject  unrentedObject = new RentedObject(this, newObject, MinimumUnrentedIndex);
                        PooledObjects[MinimumUnrentedIndex] = unrentedObject;
                        MinimumUnrentedIndex++;
                        CreatedObjectCount++;
                        return(unrentedObject);
                    }

                    // Reuse pooled object at current index or move onto the next.
                    RentedObject pooledObject = PooledObjects[MinimumUnrentedIndex];

                    if (!pooledObject.IsRented)
                    {
                        pooledObject.IsRented = true;
                        return(pooledObject);
                    }

                    MinimumUnrentedIndex++;
                }
            }
#else
            return(new RentedObject(this, ObjectConstructor(), 0));
#endif
        }