调用该功能后,C#Out of Memory错误

时间:2016-10-05 21:56:23

标签: c#

我正在尝试解压缩大量数据,并使用以下代码。第一次迭代结束就好了,然后在下一次迭代中我得到一个错误: "类型' System.OutOfMemoryException'的例外情况发生在mscorlib.dll中但未在用户代码"

中处理
private static void UnCompressP(byte[] buffToUnCompress, int index, AutoResetEvent eventToTrigger, ref MemoryStream[] memStream)
{
    eventToTrigger.Set();
    MemoryStream cmpStream = new MemoryStream(buffToUnCompress);

    GZipStream unCompZip = new GZipStream(cmpStream, CompressionMode.Decompress, true);

    byte[] unCompressedBuffer = new byte[buffToUnCompress.Length];

    MemoryStream msToAssign = new MemoryStream();
    int read = 0;
    while (0 != (read = unCompZip.Read(unCompressedBuffer, 0, buffToUnCompress.Length)))
    {
        msToAssign.Write(unCompressedBuffer, 0, read);
        msToAssign.Flush();
    }
    memStream[index] = msToAssign;

    unCompZip.Close();
    cmpStream.Close();

}

1 个答案:

答案 0 :(得分:0)

你没有处置任何东西。需要通过调用Dispose()方法处理每个流,或者最好将其与using { }

一起封闭

这应该足够了,但是如果你对内存非常关键,你可能无法等待垃圾收集器回收内存,所以你可能还需要在方法结束时调用垃圾收集器:

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;   
GC.Collect();
GC.WaitForPendingFinalizers();