microsoft/Microsoft.IO.RecyclableMemoryStream

FileStreamResult: ObjectDisposedException: Cannot access a disposed object.

vitali-karmanov opened this issue · 4 comments

Hello,

What is the right way of using a RecyclableMemoryStreamManager with FileStreamResult? I'm having the following issue:

image
public class PdfFileAttachment
{
    public byte[] FileBytes { get; set; }
    public string ContentType { get; set; }
}

PdfFileAttachment pdfFileAttachment = await _pdfService.GetPdfFileAttachment();

var options = new RecyclableMemoryStreamManager.Options()
{
    BlockSize = 1024,
    LargeBufferMultiple = 1024 * 1024,
    MaximumBufferSize = 16 * 1024 * 1024,
    GenerateCallStacks = true,
    AggressiveBufferReturn = true,
    MaximumLargePoolFreeBytes = 16 * 1024 * 1024 * 4,
    MaximumSmallPoolFreeBytes = 100 * 1024,
};

var manager = new RecyclableMemoryStreamManager(options);

using (var memoryStream = manager.GetStream())
{
    memoryStream.Write(pdfFileAttachment.FileBytes, 0, pdfFileAttachment.FileBytes.Length);
    
    return new FileStreamResult(memoryStream, pdfFileAttachment.ContentType);
}

The end goal is to return a pdf file that is stored in a byte[].

Thank you!

If I remove the using and I added pdfFileStream.Seek(0, SeekOrigin.Begin) before the return it works.

public class PdfFileAttachment
{
    public byte[] FileBytes { get; set; }
    public string ContentType { get; set; }
}

PdfFileAttachment pdfFileAttachment = await _pdfService.GetPdfFileAttachment();

var options = new RecyclableMemoryStreamManager.Options()
{
    BlockSize = 1024,
    LargeBufferMultiple = 1024 * 1024,
    MaximumBufferSize = 16 * 1024 * 1024,
    GenerateCallStacks = true,
    AggressiveBufferReturn = true,
    MaximumLargePoolFreeBytes = 16 * 1024 * 1024 * 4,
    MaximumSmallPoolFreeBytes = 100 * 1024,
};

var manager = new RecyclableMemoryStreamManager(options);

var memoryStream = manager.GetStream();

memoryStream.Write(pdfFileAttachment.FileBytes, 0, pdfFileAttachment.FileBytes.Length);

pdfFileStream.Seek(0, SeekOrigin.Begin);

return new FileStreamResult(memoryStream, pdfFileAttachment.ContentType);

However, doesn't removing the using kind of defeat the purpose of the RecyclableMemoryStream by not disposing the stream?

Thank you!

When you dispose of the stream, the recyclable buffers, which act as storage for the stream, are returned to their pool. It's important to dispose of the stream, but make sure to do this after you've processed the FileStreamResult you're returning. The Dispose() method call, whether explicit or implicit through the using() statement, should be made from outside the method that creates and returns the FileStreamResult.