Search code examples
vb.netgarbage-collectiondispose

In VB/C# .NET, does a dialog always have to be disposed of manually?


I'm looking into disposing of resources and getting a little mixed up over the different ways to do it.

I've just found out that using Close() on a form shown with ShowDialog() only actually hides it and doesn't completely kill it off, so to speak. While this is useful for what I want at the moment, I'm now worrying about memory leaks elsewhere.

After using ShowDialog(), should I always call Dispose() on the form or use a Using block? Is there a difference? Or will the form be automatically disposed of when exiting the subroutine is was created in? For example, one of my typical simple usages:

Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
Dim frm As New frmSomething()
frm.ShowDialog()

'frm is exited by clicking the X or using Close()
'At this point, frm is still in memory.  Is it automatically disposed of
'after the End Sub here, or should I do frm.Dispose() ?

End Sub

Solution

  • It won't be automatically disposed, no. It may well not cause a problem, and there may well be a finalizer to do everything that's required, so the cost would just be some extra resources before the finalizer runs (and a longer delay before eventual GC) but it would be better to dispose it explicitly - ideally with a Using statement:

    Using frm As New frmSomething()
        frm.ShowDialog()
    End Using