Alex Rivera | Logout

Do I need to call Dispose() on managed objects?

Asked 2010-03-30T20:57:07.047
29

I can't believe I'm still confused about this but, any way, lets finally nail it:

I have a class that overrides OnPaint to do some drawing. To speed things up, I create the pens, brushes etc before hand, in the constructor, so that OnPaint does not need to keep creating and disposing them.

Now, I make sure that I always dispose of such objects, but I have the feeling I don't need to because, despite the fact they implement IDisposable, they're managed objects.

Is this correct?


Thanks for all the answers, the issue has certainly been nailed.
I'm glad I've been vigilant in always using 'using' so that I don't need to go through all my code checking. I just wanted to be clear that I wasn't being a pointless user.

As an aside, I did have a strange situation, recently, where I had to replace a using block and manually call dispose! I'll dig that out and create a new question.

Edit
Report

1 Answer

2

Have you profiled this to see if Creating & Disposing these objects really is a problem? I don't think it is.

You make things a lot easier for yourself and certainly less error prone by just following the create-in-a-using-block pattern.

If you do want to create them once, then also implement IDisposable on your owning class and iterate the Dispose over your owned objects. No need for a destructor (finalizer).

There is almost no cost on doing this to objects that don't actually need Dispose, but there is a big cost if you forget Dispose on an object that does need it.

answered 2010-03-30T21:06:16.790

Your Answer