示例#1
0
        /// <summary>
        /// Creates a new ObjectPool.
        /// </summary>
        /// <param name="actionCreate">Use to create a new instance when the pool is empty. In most cases this will just be <code>() => new T()</code></param>
        /// <param name="actionOnGet">Called when the instance is being taken from the pool.</param>
        /// <param name="actionOnRelease">Called when the instance is being returned to the pool. This could be used to clean up or disable the instance.</param>
        /// <param name="concurrent">When set to `true` enables thread-safe implementation variant. The default value is `false`. </param>
        /// <param name="collectionCheck">Collection checks are performed when an instance is returned back to the pool. An exception will be thrown if the instance is already in the pool. Collection checks are only performed in the Editor.</param>
        /// <param name="defaultCapacity">The default capacity the stack will be created with.</param>
        /// <param name="maxSize">The maximum size of the pool. When the pool reaches the max size then any further instances returned to the pool will be ignored and can be garbage collected. This can be used to prevent the pool growing to a very large size.</param>
        public ObjectPool(
            Func <T> actionCreate,
            Action <T> actionOnGet     = null,
            Action <T> actionOnRelease = null,
            bool concurrent            = false,
            bool collectionCheck       = true,
            int defaultCapacity        = k_UnsetCapacityValue,
            uint maxSize = 10000)
        {
            if (maxSize == 0)
            {
                throw new ArgumentException("Limit must be greater than 0", nameof(maxSize));
            }

            if (defaultCapacity != k_UnsetCapacityValue && concurrent)
            {
                throw new ArgumentException("Concurrent pool variant can't have custom default capacity.", nameof(defaultCapacity));
            }

            if (concurrent)
            {
                m_PoolStack = new ConcurrentPoolStackProxy <T>();
            }
            else
            {
                m_PoolStack = defaultCapacity != k_UnsetCapacityValue
                    ? new PoolStackProxy <T>(defaultCapacity)
                    : new PoolStackProxy <T>();
            }

            m_ActionCreate    = actionCreate ?? throw new ArgumentNullException(nameof(actionCreate));
            m_MaxSize         = maxSize;
            m_ActionOnGet     = actionOnGet;
            m_ActionOnRelease = actionOnRelease;
            m_CollectionCheck = collectionCheck;
        }