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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With