Search code examples
c#compact-framework

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);
    }
}

Solution

  • 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);
        } 
    }