Monday, December 17, 2007

Avoid Memory Leaks with PictureBox

I had a situation where I had a memory leak with a PictureBox, I did something like this:
            Dim bm_out As New Bitmap(Width, Height)
            Dim gr_out As Graphics = Graphics.FromImage(bm_out)           
            gr_out.DrawImage(...)
            FullImage.Image = bm_out

Now everytime this block of code was called, when the New Bitmap was created we created a new block of memory.  When I left this function, I was constantly losing memory.  The reason for this is that FullImage.Image was pointing to a block of memory, and when I called FullImage.Image = bm_out, I pointed it to a new block of memory, and lost the pointer to the previous block of memory.  But that previous block of memory was still allocated.  So I had a memory leak.  The solution was this one line, before FullImage.Image = bm_out
            FullImage.Image.Dispose()

So the code like this did not have the memory leak.
            Dim bm_out As New Bitmap(Width, Height)
            Dim gr_out As Graphics = Graphics.FromImage(bm_out)           
            gr_out.DrawImage(...)
            FullImage.Image.Dispose()
            FullImage.Image = bm_out

No comments: