i have a modeless form. When the user is done with it, and they Close it, the form (and its associated resources) are no longer needed.
Correct programming demands that i dispose of anything that implements IDisposable (i.e. i cannot wait for a garbage collection to run). This includes myself, a WinForms Form.
What is the best or valid time for a form to call Dispose on itself?
In “other” languages, you could destroy a form from within the form
itself by callingRelease:void CloseButton(EventArgs e) { this.Release(); }This method causes the form to be destroyed after every instance
method has returned (and the form has processed all pending messages).In this “other” language, it would be horribly wrong to call:
void CloseButton(EventArgs e) { this.Free(); }Because i am then freeing the object that i am running an method on out from under myself;
which causes an access violation momentarily.
i assume it dangerously invalid to call:
void CloseButton(EventArgs e)
{
this.Dispose();
}
But maybe it’s safe to call:
void FormClosed(EventArgs e)
{
this.Dispose();
}
What’s the guidance on a modeless form cleaning up itself when it’s no longer needed?
Turns out you don’t even need to call
Disposeon a modeless form. From MSDN:So to answer my question, “What would be a good time for my modeless form to dispose of itself?”
Answer: Never