Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemoryException in C#

This code causes some kind of memory leak. I assume it's caused by the new byte[]. But shouldn't the GC avoiding this? If the program runs long enough, the code will cause a OutOfMemoryException

using (var file = new FileStream(fileLoc, FileMode.Open))
{
    int chunkSize = 1024 * 100;
    while (file.Position < file.Length)
    {
        if (file.Length - file.Position < chunkSize)
        {
            chunkSize = (int)(file.Length - file.Position);
        }
        byte[] chunk = new byte[chunkSize];
        file.Read(chunk, 0, chunkSize);
        context.Response.BinaryWrite(chunk);
    }
}
like image 853
chriszero Avatar asked Aug 29 '26 22:08

chriszero


1 Answers

The problem is almost certainly that you're repeatedly allocating new arrays and in memory they're allocated as contiguous blocks, so I can understand how it's chewing through it.

How about rejigging things slightly so that you only create the buffer once and then reuse it unless you get into the if where the chunksize required is less than the standard chunk size.

using (var file = new FileStream(fileLoc, FileMode.Open)) {
    int chunkSize = 1024 * 100;
    byte[] chunk = new byte[chunkSize];

    while (file.Position < file.Length) {
        if (file.Length - file.Position < chunkSize) {
            chunkSize = (int)(file.Length - file.Position);
            chunk = new byte[chunkSize];
        }
        file.Read(chunk, 0, chunkSize);
        context.Response.BinaryWrite(chunk);
    } 
}
like image 62
Nanhydrin Avatar answered Aug 31 '26 15:08

Nanhydrin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!