views:

267

answers:

2

Hi,

I'm wondering whether this is a good thing or a bad thing and what I have to watchout for when calling Dispose.

I have a Tab (PageTab) that I extend and insert a Panel which has a listview and another Toolbar control into. These tabs then get inserted into a tab control (all native .NET WinForms controls).

When the user closes one of these tabs I call the Dispose method (which follows the MSDN way of implementing IDisposable.

I'm wondering whether its wise or suggested to declare the controls as ReadOnly:

protected readonly ListView _AccountsList = new ListView();
protected readonly Panel _Panel = new Panel();

because in the Dispose I just call _Panel.Dipose() etc on them but cannot set them to null. I want to avoid leaks as much as I can and have things GC'd.

Whats the best way for non-Designer GUI development and disposing them?

+1  A: 

If the tab is being closed, there presumably won't be any other references to it, so you don't need to worry about setting the values to null.

The only value in setting variables to null for the sake of GC is in cases where there would otherwise still be live references to the object. It doesn't sound like that's the case here.

Jon Skeet
+3  A: 

The default implementation of Control.Dispose (inherited by TabPage) is quite sufficient. It iterates the child controls as stored in the Controls collection member and calls their Dispose() method. You don't have to help.

There are only two cases where you should call Dispose() explicitly:

  • When you remove a control from the Controls collection. Calling Dispose() here is a hard requirement. Not doing so will keep the window handle alive for the life of the program, it is just not visible. You'll have a leak if you don't dispose it.
  • When you show a form with ShowDialog(). This bypasses the normal automatic disposal of a form and its child controls, necessarily so that you can read back the dialog result without risking an ObjectDisposed exception. The using statement is the proper way to do this.

The latter case is not in fact a leak, the Control class' finalizer ensures that the window handle for the dialog eventually is released, assuming there are no live references left to the dialog object.

Control is one of the very few classes where forgetting to call Dispose() can in fact cause an uncontrollable resource leak. You are correct in that you have to call Dispose() explicitly on your TabPage derived object to dispose it when you remove the page. But you don't have to worry about its child controls.

Hans Passant