C#中的OutOfMemoryException

chr*_*ero 1 c# compact-framework

此代码导致某种内存泄漏.我认为它是由...引起的new byte[].但GC不应该避免这种情况吗?如果程序运行的时间足够长,代码将导致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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Nan*_*rin 6

问题几乎可以肯定是你重复分配新的数组,并且在内存中它们被分配为连续的块,所以我可以理解它是如何咀嚼它的.

如何稍微重新调整内容,以便只创建缓冲区一次,然后重复使用它,除非你进入if所需的chunksize小于标准块大小.

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)