After looking at how the Windows Forms designer handles components, I think it might be useful to have a quick look at how Controls are handled with regards to IDisposable.
Every Windows Forms control derives from the System.Windows.Forms.Control base class, which exposes the Controls property:
Public ReadOnly Property Controls() As ControlCollection
The implementation of the Control.Dispose(Boolean) is overridden in such a way that it iterates through the Controls collection calling the Dispose method for each member of the collection. The Windows Forms Designer "knows" this and the code it generates for Control-derived classes always adds controls to the Control.Controls collection that the Form class inherits from the Control class:
#Region " Windows Form Designer generated code "
...
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox
...
Me.Controls.Add(Me.TextBox1)
End Sub
...
#End Region
This way, when the Form is being disposed, the contained controls are disposed automatically as well.
If you've been designing a component that allocates UNMANAGED resources, please double check that you:
- Implement the specific
Public New(IContainer)constructor and add your component instance to the container by calling theIContainer.Add(Me)method in the constructor. (If you create your component using the Visual Studio .NET 'Component Class' template, it generates the specific constructor for you properly.) - Implement the
IDisposabledesign pattern properly meaning that you do release the unmanaged resources and also that you do that exactly once.
Comments