In addition to Solution 1:
You have two options:
- You can create your instance of
Pen
the way you do and dispose it in this Form.Dispose
method: http://msdn.microsoft.com/en-us/library/aw58wzka%28v=vs.110%29.aspx[^].
This is the approach designed to chain disposal in a set of UI elements (or some other objects you would want to design yourself) according to their parent-child relationships. - Also, you can create an instance of your pen where you use it (in your overridden
OnPaint
method or your handler of the event Paint
and dispose immediately after use. The best way to do it is using the using
statement:
using (Pen pen = new Pen(Color.Red, 1.0f))
{
for (int i = 0; i < 100; i++)
{
g.DrawLine(
p,
d.Next(Width),
d.Next(Height),
d.Next(Width),
d.Next(Height));
}
}
Not that pen.Dispose
will be called even of an exception is thrown. Please see: http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].
Unmanaged memory leaks are usual when you use GDI. The simple rule is: watch out for all objects; check up if they implement
System.IDisposable
. If they do, make sure you dispose them. See also:
http://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx[
^].
Also, managed memory leak is possible, but that could be a result of wrong design. This is a different story…
—SA