We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Aspose.Pdf.Document from stream life cycle

Hello, Aspose!

Question about life cycle of Aspose.Pdf.Document that created from stream.

I have a factory of pdf documents (> 300 documents in memory):

public class DocumentFactory : IDocumentFactory
{
    public Task<Aspose.Pdf.Document> Create(Stream stream)
    {
        return Task.Run(() =>
        {
            return new Aspose.Pdf.Document(stream);
        });        
    }
}

I create all documents on app startup like that:

public async Task<Aspose.Pdf.Document> CreateDocument(IDocumentFactory factory, byte[] bytes)
{
    var stream = new MemoryStream(bytes));    
    var document = await factory.Create(stream);    
    return document;
}

And after that i will use created documents in my application every ~5 minutes.

All works perfectly, but my question about potential memory leak while creation from stream object:
Should i dispose stream instantly after i create Aspose.Pdf.Document like in code below?

public async Task<Aspose.Pdf.Document> CreateDocument(IDocumentFactory factory, byte[] bytes)
{
    Aspose.Pdf.Document document;
    using(var stream = new MemoryStream(bytes))
    {
        document = await factory.Create(stream);
    }
    return document;
}

Or Aspose.Pdf.Document use provided stream in all life cycle of document and throw ObjectDisposedException when i trying to access to document fields or methods?
If not, should i manually dispose stream object when i remove old document from memory?

@mgkcortyw

It is better to dispose all initialized resources e.g. stream manually once a PDF document is saved. It is to prevent any data loss because API keeps all resources in the memory during PDF generation process and disallocate them once PDF document is saved or Document object is disposed. However, if you face any issue, please share a sample console application with us so that we can notice the issue in our environment and address it accordingly.