Warm tip: This article is reproduced from stackoverflow.com, please click
c# heap-memory memory-leaks out-of-memory wpf

Converting byte array to memory stream and bitmap causing high memory usage

发布于 2020-03-27 10:18:35

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. 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?

Questioner
YSFKBDY
Viewed
303
smoothumut 2019-07-05 17:32

I have tested your code and saw that the system cannot collect your garbage in a 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. 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.