Question

In my ASP.NET MVC application I am using the NPOI framework to generate a rather large excel file (30-100mb)

http://npoi.codeplex.com/

After generating the document, i save it to a memorystream, and return a FileStreamResult by using the MVC File helper method

File(Stream fileStream, string contentType, string fileDownloadName)

like this

HSSFWorkbook document = GenerateExcelWorkBook();

var stream = new MemoryStream();
document.Write(stream);

stream.Flush();
stream.Position = 0;

return File(stream, "application/vnd.ms-exce", "filename.xls");

The variable document is of type "HSSFWorkbook" from the NPOI framework

I don't get why the memory usage stays high, even after the document has been generated, and the stream has been returned to the user. The File method should dispose of the stream after writing to the response stream.

If i click the generate link again, the memory usage goes back to normal, and starts to climb as the document is being generated again.

Could this be an issue with the NPOI HSSFWorkbook class not being garbage collected properly or something? That would just be weird as i am not saving any static variables (at least not in my code anyways).

Anyone know why the memory usage won't go back to normal?

Was it helpful?

Solution

Disposing != freeing memory.

The garbage collector will free the memory as needed, and large blocks might take longer than smaller ones.

The behavior you are seeing upon generating a second document affirms what I'm suggesting; The additional memory usage causes 'memory pressure', which triggers garbage collection to clean up things.

Basically, unless you truly have some memory problems, don't worry about it.

OTHER TIPS

You MIGHT want to look at calling GC.Collect() if you're running into a low memory situation. Check this SO thread for a good explanation of why (or why not) to call it.

GC.Collect()

I'm not saying you should, just that it might be worth testing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top