Pull to refresh

Sharing .NET-experience: Streams pooling by using Microsoft.IO.RecyclableMemoryStream

Reading time1 min
Views2.9K

The pooling is the good practice to reuse created resources instead of a new allocation. I found Microsoft.IO.RecyclableMemoryStream package for using memory streams pooling during logging HTTP-requests in my server.

RecyclableMemoryStreamManager _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
using var memoryStream = _recyclableMemoryStreamManager.GetStream();
bodyStream.Seek(0, SeekOrigin.Begin);
bodyStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
string responseBody;

const int readChunkBufferLength = 4096;
using var textWriter = new StringWriter();

using (var streamReader = new StreamReader(memoryStream))
{
    var readChunk = new char[readChunkBufferLength];
    int readChunkLength;
    do
    {
        readChunkLength = streamReader.ReadBlock(readChunk,
	        0,
	        readChunkBufferLength);
        textWriter.Write(readChunk, 0, readChunkLength);
    }
    while (readChunkLength > 0);
}
bodyStream.Seek(0, SeekOrigin.Begin);
responseBody = textWriter.ToString();

Tags:
Hubs:
Total votes 2: ↑1 and ↓10
Comments0

Articles