StreamPipeReader may have a potential memory leak risk.
#123623
-
|
Recently, I have been using private BufferSegment AllocateSegment(int? minimumSize = null)
{
BufferSegment nextSegment = CreateSegmentUnsynchronized();
var bufferSize = minimumSize ?? BufferSize;
int maxSize = !_options.IsDefaultSharedMemoryPool ? _options.Pool.MaxBufferSize : -1;
if (bufferSize <= maxSize)
{
// Use the specified pool as it fits.
int sizeToRequest = GetSegmentSize(bufferSize, maxSize);
nextSegment.SetOwnedMemory(_options.Pool.Rent(sizeToRequest));
}
else
{
// Use the array pool
int sizeToRequest = GetSegmentSize(bufferSize, MaxBufferSize);
nextSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(sizeToRequest));
}
return nextSegment;
}
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
Not returning a rented array to its pool doesn't cause memory leaks alone, just makes it useless (compared to normal gc allocation). The array seems to be returning to the pool inside |
Beta Was this translation helpful? Give feedback.
What? No.
You don't need the class (since the slice would already be length-limited), and whatever
WriteAsync(...)is should be takingReadOnlyMemory<byte>which you can get directly from (iterating through) the sequence, so there's no reason to get an array copy of the data either.Also, in some cases sending an array to another method is supposed to relinquish ownership of it, so it may not be safe to return the array after passing it to another method.
That said:
CopyToAsync(...), and not bother with anything at this point in the pipeline. Using pipes is mostly meant for de/serializing, and …