Should I dispose GDI+ object before its creation?
Is recommended to always Dispose GDI+ object after using it.
by e.g.
Pen p = new Pen(Color.Green);
// use 'p'
p.Dispose();
now, if I have this situation:
Pen p = new Pen(Color.Green);
// use green 'p'
p = new Pen(Color.Red); // Should I Dispose my 'p' first?
// use red 'p'
p.Dispose();
EDIT A:
Using 'USING' is not possible every time.
private Pen p;
public RefreshPen(style)
{
// p.Dispose(); +-
p = new Pen(style.Color);
// e开发者_运维问答tc.
}
EDIT B:
Will this be OK?
using (Pen p = new Pen(Color.Green))
{
// use green 'p'
p = new Pen(Color.Red); // Should I Dispose my 'p' first?
// use red 'p'
p = new Pen(Color.Blue); // Should I Dispose my 'p' first?
// use blue 'p'
}
Yes, you should. (Also note that the using
statement is a tremendous help here. I very rarely call .Dispose explicitly. using
takes care of that.)
Yes. You are creating a new object and assigning it to p, which means you should dispose the old object.
I might code it like so:
using(Pen p = new Pen(Color.Green))
{
//do some stuff
}
using(Pen q = new Pen(Color.Red))
{
//do some other stuff
}
This prevents you from forgetting to dispose the pen, or using a disposed object.
Can't you just change the properties of the object?
Pen p = new Pen(Color.Green);
//use it here.
p.Color = Color.Red;
//use it some more.
p.Dispose();
精彩评论