Microsoft.AspNet.Server.Kestrel.Infrastructure.MemoryPool2.Lease C# (CSharp) Method

Lease() public method

Called to take a block from the pool.
public Lease ( int minimumSize ) : Microsoft.AspNet.Server.Kestrel.Infrastructure.MemoryPoolBlock2
minimumSize int The block returned must be at least this size. It may be larger than this minimum size, and if so, /// the caller may write to the block's entire size rather than being limited to the minumumSize requested.
return Microsoft.AspNet.Server.Kestrel.Infrastructure.MemoryPoolBlock2
        public MemoryPoolBlock2 Lease(int minimumSize)
        {
            if (minimumSize > _blockLength)
            {
                // The requested minimumSize is actually larger then the usable memory of a single block.
                // Because this is the degenerate case, a one-time-use byte[] array and tracking object are allocated.
                // When this block tracking object is returned it is not added to the pool - instead it will be 
                // allowed to be garbage collected normally.
                return MemoryPoolBlock2.Create(
                    new ArraySegment<byte>(new byte[minimumSize]),
                    dataPtr: IntPtr.Zero,
                    pool: null,
                    slab: null);
            }

            while (true)
            {
                MemoryPoolBlock2 block;
                if (_blocks.TryPop(out block))
                {
                    // block successfully taken from the stack - return it
                    return block;
                }
                // no blocks available - grow the pool and try again
                AllocateSlab();
            }
        }

Usage Example

        public void CopyToCorrectlyTraversesBlocks()
        {
            using (var pool = new MemoryPool2())
            {
                var block1 = pool.Lease(128);
                var block2 = block1.Next = pool.Lease(128);

                for (int i = 0; i < 128; i++)
                {
                    block1.Array[block1.End++] = (byte)i;
                }
                for (int i = 128; i < 256; i++)
                {
                    block2.Array[block2.End++] = (byte)i;
                }

                var beginIterator = block1.GetIterator();

                var array = new byte[256];
                int actual;
                var endIterator = beginIterator.CopyTo(array, 0, 256, out actual);

                Assert.Equal(256, actual);

                for (int i = 0; i < 256; i++)
                {
                    Assert.Equal(i, array[i]);
                }

                endIterator.CopyTo(array, 0, 256, out actual);
                Assert.Equal(0, actual);
            }
        }
All Usage Examples Of Microsoft.AspNet.Server.Kestrel.Infrastructure.MemoryPool2::Lease