C# Memory leak in Bitmap

Update: You don't have a memory leak per se, you just have to wait for the Garbage Collector to free up the resources.

If you do want to make the garbage collector collect though, you can do this:

System.GC.Collect();
System.GC.WaitForPendingFinalizers();

Why do you need to dispose of the bitmap? If your PictureBox is using it, then you need the bitmap. If you're changing it a lot, maybe you should switch out the old bitmap for a new one and dispose of the old one:

Bitmap bmp1 = new Bitmap(2480, 3508);
panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
Image img = pictureBox1.Image;
pictureBox1.Image = bmp1;
if (img != null) img.Dispose(); // the first time it'll be null

I assume you should dispose only the image you don't need anymore. You still need the bmp1 created, you just set it to be the content of the pictureBox2.Image field . Try something along these lines:

Bitmap bmp1 = new Bitmap(2480, 3508);
panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
Bitmap bmp2 = (Bitmap)pictureBox2.Image;
pictureBox2.Image = bmp1;
bmp2.Dispose();

Disclaimer: I'm not experienced with C#, so I might be wrong...

Tags:

C#

Image

Bitmap