Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Memory leak in Bitmap

Tags:

c#

image

bitmap

I got a memory leak in my application in this lines.. If i take a look in the task manager, every time when this process is triggered, the RAM memory is increasing by +- 300 MB..

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

Can someone help me with his leak? If I use:

bmp1.Dispose();

I get an exception in "Program.cs" at this line: Application.Run(new Form1()); And after this, the application is stopped running...

Screen application: enter image description here

like image 684
Ferry Jongmans Avatar asked Feb 19 '13 12:02

Ferry Jongmans


2 Answers

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(); // this may be null on the first iteration
like image 88
Adam K Dean Avatar answered Oct 25 '22 04:10

Adam K Dean


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

like image 42
ppeterka Avatar answered Oct 25 '22 04:10

ppeterka