简体   繁体   English

将字节数组转换为内存流和位图会导致大量内存使用

[英]Converting byte array to memory stream and bitmap causing high memory usage

I have a byte array list. 我有一个字节数组列表。 And, I am using it to generate bitmap images via memory stream. 而且,我正在使用它通过内存流生成位图图像。

While saving images, memory usage goes very high. 保存图像时,内存使用率很高。 And at some point, it causes out of memory exception. 在某些时候,它会导致内存不足异常。

I tried to comment out saving files to see if that causing this problem. 我试图注释掉保存文件以查看是否导致此问题。 Or, called GC manually. 或者,手动调用GC。 Nothing changed, still using high memory. 什么都没改变,仍然使用高内存。 My latest code is like this: 我最新的代码是这样的:

List<byte[]> byteArrayList = helper.GetArrayList(); // Gets approximately 10k items.

for (int i = 0; i < byteArrayList.Count; i++)
{
    using (MemoryStream ms = new MemoryStream(byteArrayList[i]))
    {
        using (Bitmap bm = new Bitmap(ms))
        {
            bm.Save(fileLocation);

            bm.Dispose();
        }

        ms.Dispose();
    }

    byteArrayList[i] = null;

    byteArrayList.Remove(byteArrayList[i]);
}

byteArrayList.Dispose();

How can i solve this issue? 我该如何解决这个问题?

If you change the helper method to return a Queue<T> instead... 如果更改辅助方法以返回Queue<T>代替...

Queue<byte[]> byteArrayQueue = helper.GetQueue(); // Gets approximately 10k items.

while (byteArrayQueue.Any())
{
    using (var ms = new MemoryStream(byteArrayQueue.Dequeue()))
    {
        using (var bm = new Bitmap(ms))
        {
            bm.Save(fileLocation);
        }
    }
}

I have tested your code and saw that the system cannot collect your garbage in a LOOP. 我已经测试了您的代码,发现系统无法在LOOP中收集您的垃圾。 so if you create so many bitmaps in a loop, the memory increases to the peak levels (such 2-3-4 gbs) until garbage collector runs. 因此,如果您在一个循环中创建了很多位图,则内存将增加到峰值级别(例如2-3-4 gbs),直到运行垃圾收集器。 But when loop ends, the memory level decreases to the normal which is too late. 但是当循环结束时,内存级别降低到正常水平,为时已晚。 So When I test your code in a BACKGROUNDWORKER instead of main thread, GC doesnt stuck to the loop and runs as it is supposed to and it converts the byte arrays to the bitmaps and save them without any extreme memory consumption. 因此,当我在BackgroundWORKER(而不是主线程)中测试您的代码时,GC不会卡在循环中并按预期运行,它将字节数组转换为位图并保存它们而没有任何极端的内存消耗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM