C# Form.Close vs Form.Dispose
Asked Answered
V

8

102

I am new to C#, and I tried to look at the earlier posts but did not find a good answer.

In a C# Windows Form Application with a single form, is using Form.Close() better or Form.Dispose()?

MSDN says that all resources within the object are closed and the form is disposed when a Close is invoked. Inspite of which, I have come across several examples online which follow a Dispose rather than a Close.

Does one have an advantage over the other? Under which scenarios should we prefer one over the other?

Vaporization answered 22/6, 2010 at 21:41 Comment(6)
Slightly different question, same answer, IMO: i.e. Close and Dispose are usually equivalent, except that you can call Close more than once.Schatz
@Chrisw: You can also call Dispose more than once.Octillion
@ChrisW, Dispose should be designed to run more than once as well. bluebytesoftware.com/blog/…Convexoconcave
The thing that got me that close === dispose rather than close == form.Visible = false ; I was expecting that close would be a softer method than dispose.Earring
@Pete Kirkham: If you want form.Visible = false; you can call form.Hide(). In fact, form.Hide() simply sets this.Visible = false;.Vincenz
Do I need to Dispose a Form after the Form got Closed?Dielu
D
194

This forum on MSDN tells you.

Form.Close() sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.

If you do a form1.Show() or Application.Run(new Form1()), Dispose will be called when Close() is called.

However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you'll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself.

Disposable answered 22/6, 2010 at 21:44 Comment(5)
Did the 1st version include the quote? +1 to compensate.Octillion
@Dan the first version sucked... (Sorry @Kyra)Hokku
This is somewhat not the same as MSDN states at msdn.microsoft.com/en-us/library/…: "The one condition when a form is not disposed on Close is when it is part of a multiple-document interface (MDI) application, and the form is not visible. In this case, you will need to call Dispose manually to mark all of the form's controls for garbage collection." However, it should be easy to check whether modal forms are disposed or not with a simple sample.Vincenz
Do I need to Dispose a Form after closing the Form?Dielu
Thanks for the explanation. Might want to fix the link though :)Viewpoint
E
16

As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.

Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.

In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.

Elly answered 22/6, 2010 at 21:54 Comment(1)
E
8

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

Ennoble answered 22/6, 2010 at 21:47 Comment(2)
If you dispose the form, then closing and closed events are not called.Susumu
calling Dispose method would cause flickering of the window when used on Modal-Form over mdi-child windowDapsang
D
4

An old question, having some good answers, but I want to share a clear answer for this very popular question


How do I close Form in code?

  • Did you open the form using Show?

    Then to close it in code, just call Close().

  • Did you open the form using ShowDialog?

    Then close it by Close or by setting DialogResult.

Do I need to dispose Form?

  • Did you open the form using Show?

    No you don't need. After you close the form by Close or by clicking on X, it will be disposed automatically.

  • Did you open the form using ShowDialog?

    Yes you need. After you close the form by Close or by setting DialogResult or by clicking on X, if you are not going to reuse the form, you need to explicitly call Dispose, or make sure you create the form instance in a using block like this:

    //form will be disposed after the using block
    using (var f = new MyForm())
    {
        if (f.ShowDialog() == DialogResult.OK)
        {
            //Your logic to handle OK here
        }
    }
    

    If you want to reuse it later, then do not forget to explicitly Dispose in when you no more need it.

Dielu answered 18/2, 2022 at 9:58 Comment(0)
H
1

Using usingis a pretty good way:

using (MyForm foo = new MyForm())
{
    if (foo.ShowDialog() == DialogResult.OK)
    {
        // your code
    }
}
Handicraftsman answered 28/2, 2018 at 17:29 Comment(0)
C
0

Close() - managed resource can be temporarily closed and can be opened once again.

Dispose() - permanently removes managed or not managed resource

Creek answered 17/12, 2018 at 5:29 Comment(1)
This is true only if the form was shown using ShowDialog(). Otherwise,Close() will dispose the form as well.Taffy
D
-1

If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!

Dupuis answered 17/8, 2019 at 17:39 Comment(0)
F
-1

What I have just experiment with VS diagnostic tools is I called this.Close() then formclosing event triggered. Then When I call this.Dispose() at the end in Formclosing event where I dispose many other objects in it, it cleans everything much much smoother.

Feodora answered 5/11, 2019 at 5:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.