How deep does Controls.Clear() clean up?

前端 未结 2 1213
心在旅途
心在旅途 2021-02-20 16:57

I\'m using a TableLayoutPanel which is dynamically filled with other TablelayoutPanels.

Now I\'m wondering what happens when I call Table

相关标签:
2条回答
  • 2021-02-20 17:39

    There is a bit of confusion in your question. Clear() will remove references and objects will be collected by garbage collector.

    But, you are also using the word dispose. Cleared objects will not be disposed in the sense that their Dispose method will be called.

    Thus, if you are not using those objects anymore, and you want Dispose to be called on them, you have to do it yourself.

    0 讨论(0)
  • 2021-02-20 17:46

    Clear doesn't dispose the controls, leading to a memory leak. From the link:

    Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

    Since disposing within a loop messes up the indexing, you can either copy the control collection to another list and perform a ForEach loop on them or use a backwards For loop.

     for (int i = myTableLayoutPanelControls.Count - 1; i >= 0; --i) 
        myTableLayoutPanelControls[i].Dispose();
      
    

    Calling Dispose will remove the controls from memory (when the GC picks it up). This will also handle the calling of the child control's Dispose method.

    One catch is if you've got a custom control that implements IDisposable or you're overriding the Dispose method without calling the base method. In your object's Dispose method you need to ensure that you've unsubscribed from any events outside your scope. If you don't, that reference will keep your object alive.

    0 讨论(0)
提交回复
热议问题