A default form Dispose function will look something like this:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
The normal Dispose Pattern calls for releasing your managed resources:
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
Including deregistering from events:
Is it good practice to unregister from external events in the Dispose method of an IDiposable class?
Is it bad to not unregister event handlers?
Should I always disconnect event handlers in the Dispose method?
As far as I understand it, the purpose of unregistering events is to break the circular reference that keeps the garbage collector at bay:
But many opinions state that you don't need to break this loop if the item you've subscribed to is "short lived" or owned by the form and built with the designer.
Does components.Dispose() or base.Dispose(disposing) somehow set my local private System.Windows.Forms.Button button1 reference to null or unregister my event handler this.button1.Click += new System.EventHandler(this.button1_Click);? It doesn't look like components is ever initialized, so components.Dispose() won't even be run? We want button1 to be short lived and go away with the form, but don't we have a reference loop here that prevents the garbage collector from cleaning up either?
