Search code examples
c#disposegraphic

Graphics, dispose before reuse?


I want to know, should i dispose a Graphic object before reusing it? meaning i replace it´s value:

graphic = "createGraphic"

something like that, should i dispose before that?

here is an example code where i use it:

                        gmp.DrawImage(newImage, 0, 0);
                        if (newImage.Size != panelm.Size)
                        {
                            panelm.Invoke((MethodInvoker)delegate { panelm.Size = newImage.Size; });
                            this.Invoke((MethodInvoker)delegate { this.Size = newImage.Size; });
                            gmp.Dispose();
                            gmp = panelm.CreateGraphics();
                        };

So, this is in a while loop, before the while, i make gmp inherit panelm. But, i never dispose of it in the loop, i just reuse it all the time, Except, if the sizes don´t match.

Then i need to recreate it (else it´s to big/small).

But now the thing is, should i dispose before, or should i just use creategraphic?

Also, the problem here is. I can´t use, "Using" on gmp. Cause if i do, i only have 2 possibilities.

1: create it before the while loop, and reuse it until the while loop ends ( meaning, i can never change it). 2: create it inside the while loop, (meaning it will be recreated every loop which i think will be a waste).

Thanks


Solution

  • So you're asking if you should call Dispose() on it before you give it a new value?

    Graphics gmp = panelm.CreateGraphics();
    //do work
    gmp.Dispose();
    gmp = panelm.CreateGraphics();
    

    versus

    Graphics gmp = panelm.CreateGraphics();
    //do work
    gmp = panelm.CreateGraphics();
    

    As good practice, you should call Dispose() when you're done; although it will automatically get cleaned up by the garbage collector sometime if you don't, so you're not leaking resources either way.