The difference between show and ShowDialog in C# open and switch interface code

Recently, I was developing a C# project and found that the [memory] usage of the program was rising rapidly. After repeated searches, I finally found the reason. It is caused by improper use of the show statement during the switching between the main interface and the sub-interface.

The original code for switching from Form1 to Form2 interface is as follows:

Form2 dlg = new Form2();
Dlg.show();
this.Hide();

The code to return Form1 from the sub-interface Form2 is as follows:

Form1 dlg = new Form1();
Dlg.show();
this.Hide();

In fact, here, memory will be constantly created and new interfaces will be opened, which will lead to a sharp increase in memory. Show is to display a non-modal form. After modification and testing, it is best to use ShowDialog to display a modal form in such cases. The modified correct standard writing is as follows.

The original code for switching from Form1 to Form2 interface is as follows:

Form2 dlg = new Form2();
this.Hide();
dlg.ShowDialog(); //The following statement is executed only when the subform is closed 
this .Show();

The code to return Form1 from the sub-interface Form2 is as follows:

this .close(); //Close the current Form2 form directly

After this modification, the test found that the memory did not keep increasing. After the subform is closed, the occupied memory is released. I purposely share the summary of this problem, hoping to help everyone.

Leave a Comment

Your email address will not be published. Required fields are marked *