Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Pen.Dispose dispose of the underlying brush?

Tags:

c#

vb.net

gdi+

I create a new Pen Object:

Private NewPen As New Pen(New SolidBrush(Color.FromArgb(12,52,220)))

When I now call NewPen.Dispose does it also dispose of the SolidBrush I used to create the pen, or do I have to dispose of it separately?

like image 776
Jens Avatar asked Dec 25 '22 01:12

Jens


2 Answers

Simple answer: no. The Pen class (click to view the .net source code) doesn't store any references to the brush. You are responsible for disposing the brush. That's why this returns False:

Using b As New SolidBrush(Color.Black)
    Using p As New Pen(b)
        Debug.WriteLine("Is equal: {0}", (b Is p.Brush))
    End Using
End Using
like image 23
Bjørn-Roger Kringsjå Avatar answered Dec 27 '22 15:12

Bjørn-Roger Kringsjå


No. The Private keyword in your snippet is the only real hint that you are making a mistake. That implies that you made the pen a field of a class. That's never the correct thing to do, drawing objects are very cheap to create (about a microsecond) but expensive to keep around. They get allocated on a desktop heap that all programs that run on that desktop need to share. You never want to occupy space in that heap needlessly.

Always create a drawing object at the moment you need it. Which lets you fall in the pit of success with the Using statement:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    Using sbr = New SolidBrush(Color.FromArgb(12, 52, 220))
        Using pen = New Pen(sbr)
            '' Use the pen
            ''....
        End Using
    End Using
 End Sub

This tends to be pretty unintuitive to many programmers, they usually learn that keeping objects around and re-using them is a Good Thing. The general rule you'd want to keep in mind is that it is usually the reverse for disposable objects. There are some types of objects that are expensive to create so seem to warrant keeping them around. The .NET Framework however always makes an effort to cache them itself. The Font class is a good example.

like image 197
Hans Passant Avatar answered Dec 27 '22 16:12

Hans Passant