Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

.NET 

Tab not disposing

Hi all,

I have a tab control which a user can dynamically add tabs and remove tabs.
The tabs contain controls that use up resources (specifically a connect to a SQL DB and numerous table adapters). Naturally, when a tab is opened, the processor and memory usage goes up. The issue is when the tab is closed, the usage doesn't drop again. Any idea what causes this?

Thanks, Josh
First thing that comes to mind is to loop through and dispose all child controls on the tab page to be closed, then get rid of it.
or create control in runtime:
example
Code
//tab control event
public override void OnControlAdded(args blalba)
{
  if (e.Control is TabPage)
{
   var page = e.Control as tabpage;
   using (var button = new button() { //here properties like location and size})
    {
      button.Click += (sender,args) => //sql connection;
page.Controls.Add(button);
    }
//using dispos object automatically
}

}

i haven't tried it on visual studio
(Sep 11, 2015 06:44 AM)Odus Wrote:  First thing that comes to mind is to loop through and dispose all child controls on the tab page to be closed, then get rid of it.

I do this:

Code
Private Sub disposeControls(ByVal c As Control)
      If c.Controls.Count > 0 Then
      For Each ctrl As Control In c.Controls
            disposeControls(ctrl)
      Next
      End If
      c.Dispose()
    End Sub

And when I want to remove a tab I use:

Code
Dim tp As TabPage = 'Code to get the tab I want
disposeControls(tp)
TabControl1.TabPages.Remove(tp)
Don't forget to call Dispose on the TabPage itself. Also for your control arg, you can use HasChildren property:

Code
Private Sub DisposeControl(ctrl As Control)
    If ctrl.HasChildren Then
      For Each c As Control In ctrl.Controls
      DisposeControl(c)
      Next
    End If

    ctrl.Dispose()
End Sub

If this is definitely the source of the leak, are all your resources used by whatever a control calls are being disposed as well? I can't imagine controls being the only factor.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by PawnhubMay 15, 2019 11:06 PM 0 155 May 15, 2019 11:06 PM
Last Post: Pawnhub
[C#] by kevy42Aug 17, 2017 03:47 PM 4 179 Aug 17, 2017 03:47 PM
Last Post: kevy42
[C#] by severosSep 11, 2015 04:03 PM 3 181 Sep 11, 2015 04:03 PM
Last Post: Nikey646