开发者

Where should i dispose a sub form

I have FormA that creates another form, FormB, when a button is pressed.

Where开发者_运维知识库 should i dispose FormB. Is it OK to dispose FormB in FormA Closing event?


When FormB is closed (with the .Close method) it will be disposed so you don't need to manually call the .Dispose method.


When FormB is closed by clicking the X or other possiblities where it is just hidden it is not disposed. If that form in that instance occurs often, dispose it when in FormA or application exit. If that form is not opened that often you can even dispose in in the click-event-handler of the button. There it is possible with the using keyword.

using(FormB b = new FormB())
{
    if(b.ShowDialog() == DialogResult.OK) {...} else {...}
}

Of course this is only possible when it is shown modal.


 protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

you can see this in form designer.cs file it will be called when a form is closed so no need to worry about dispose


from msdn

The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.

It's better to use using:

using (var modalForm = new FormB())
{
    modalAddUser.ShowDialog();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜