YSFKBDY
YSFKBDY

Reputation: 886

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

Upvotes: 3

Views: 855

Answers (2)

smoothumut
smoothumut

Reputation: 3491

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.

Upvotes: 1

Mark Cilia Vincenti
Mark Cilia Vincenti

Reputation: 1614

If you change the helper method to return a Queue<T> instead...

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

Upvotes: 0

Related Questions