Search code examples
c#winformsgdi+dispose

Dispose graphic element in Paint eventhandler


I am working with C#, .net 3.5 and Visual Studio 2008.

After some reading about when I do have to dispose elements I am a bit confused. Would the following Paint eventhandler be ok, or would it be a Memory leak?

private void ProgressBar_Paint(object sender, PaintEventArgs e) {
        Graphics graphics = e.Graphics;
        string rightText = "rightext";
        string leftText = "lefttext";;
        string textToDraw = rightText + leftText;
        graphics.DrawString(textToDraw, progressBar.Font, 
             new SolidBrush(progressBar.ForeColor), 10, 30);                         
    }

Would this work fine then?

private void ProgressBar_Paint(object sender, PaintEventArgs e) {
        Graphics graphics = e.Graphics;
        string rightText = "rightext";
        string leftText = "lefttext";;
        string textToDraw = rightText + leftText;
        using (SolidBrush solidBrush = new SolidBrush(progressBar.ForeColor)) {
            graphics.DrawString(textToDraw, progressBar.Font, solidBrush, 18, 20);
        }
    }

Solution

  • Your first snippet has a bug, plain and simple. You really should dispose that brush. If you don't then you completely depend on the finalizer to take care of it. Which is a bit slow at getting the job done, it can only run after a garbage collection was done.

    Particularly a problem for a progress bar style control, it tends to paint itself at a high rate. Much more so than normal controls since there's, well, lots of progress if you wrote good code. If the garbage collector cannot keep up and cleanup those brushes for you then your program will crash. Happens when there are almost ten thousand brushes that need finalized, the operating system stops your program from creating more of them, kaboom.