C# Memory leak in Bitmap

bitmap, c#, image

Solution

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

Problem

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:

Original source