コード例 #1
0
        private void CacheHandle(DisposeHandle <T> handle)
        {
            // prepare the instance to be cached
            this.prepareAction?.Invoke(handle.Item);

            // attempt to return the instance to the cache
            if (Interlocked.Increment(ref cacheCount) <= Capacity)
            {
                this.cache.Add(handle.Item);
                this.itemFreedEvent.Set();
            }
            else
            {
                Interlocked.Decrement(ref cacheCount);
                handle.Item.Dispose();
            }
        }
コード例 #2
0
        public bool TryTakeItem(out DisposeHandle <T> handle)
        {
            T item;

            // attempt to take an instance from the cache
            if (this.cache.TryTake(out item))
            {
                Interlocked.Decrement(ref cacheCount);
                handle = new DisposeHandle <T>(CacheHandle, item);
                return(true);
            }
            // if no instance was available, create a new one if allowed
            else if (this.createFunc != null)
            {
                handle = new DisposeHandle <T>(CacheHandle, this.createFunc());
                return(true);
            }
            // no instance was available
            else
            {
                handle = null;
                return(false);
            }
        }