Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 385
YSFKBDY Avatar asked Feb 20 '26 10:02

YSFKBDY


1 Answers

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.

like image 69
smoothumut Avatar answered Feb 22 '26 02:02

smoothumut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!