2
votes

I know this question has already been asked, but my question is more general than the others I've seen.

When I was checking in my program my use of controls in Forms, and commands for DB(Commands, Readers, etc), the following question came to me:

If I have a Control, shouldn't I Dispose it after I use it?

That way I will make sure that my program is using only the resources that are needed, and if I must use a control that was already disposed then I'll just load it again.

Maybe there's a reason to not dispose everything always, but that's why I'm asking this question.

Thanks for any answer and I hope I made myself clear.

4
You didn't even mention or tag which language you are talking about. I guess C#? - Zoltán
Yes C#. I added the tag. Thanks - Ignacio Gómez
" And if I must use a control that was disposed " oh but you wouldn't have disposed off something if you must use later, right? - Prasanth
you have "some kind of control". Can you clarify? The control lifecycle is most of time exactly the owner window's one, as it fits in the component collection pattern. "After I use it"? How do you use your control? And to answer, dispose object you created at the end of its use. - Steve B

4 Answers

7
votes

Non-visual components you create (commands, readers, I/O components, basically anything that implements IDisposable) should be disposed after you're done with them.

For visual controls, the Form's Dispose function should dispose of all controls in it's Controls collection automatically, so you would only need to worry about controls that you remove from the form's Controls for some reason.

Unless you're experiencing serious memory problems it's probably a micro-optimization to try and dispose of form controls manually.

4
votes

Yes, if no concrete reason speaks against it, you probably should dispose everything. Controls are automatically disposed of when in a Form and the Form is disposed.

Not disposing of UI resources is not very harmful. It is just a little more memory are system resource usage than necessary. This is in most cases not a functional problem.

This is in contrast to database connections and files, of course! Disposing of them is critical.

0
votes

If you're using using unmanaged resources, then yes. Go ahead and implement IDisposable, that with the use of using will simplify your work. But not always, as for your question. Your control (UI Control) implements already this IDisposable and will be called by its parent when closing.

0
votes

Yes, you should. In Windows Forms windows (or within containers, respectively) the Form designer does it for you:

protected override void Dispose(bool disposing)
{
    if(disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}