Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods this.hide() vs this.close()

Tags:

c#

winforms

My c# windows forms application has 5 forms which I am displaying one after the another. When the user clicks on next button, the code I have given is:

new Form1().Show();
this.Hide();

However I do not want my current Form to hide. I want to close it/dispose it so that it does not consume memory. I want to release its resources like the images and variable used as soon as I am done with it. For that I tried implementing:

new Form1().Show();
this.Close();    //Form 2

but this simply closes both the forms. I even tried swapping the positions of the above two lines:

this.Close();
new Form1().Show();

but this also does same thing.

How do I release the resources of one form as soon as I am done with it? because my program throws out of memory exception when I try to re-open my Form 2 using:

new Form2().Show();
this.Hide();
like image 884
Chuker Avatar asked Oct 23 '25 16:10

Chuker


1 Answers

You can start your NewForm in a new thread and create a new message loop

When the main message loop is closed, the application exits. In Windows Forms, this loop is closed when the Exit method is called

For more information see here.

var th = new Thread(() => Application.Run(new NewForm()));
th.SetApartmentState(ApartmentState.STA); // Deprecation Fix
th.Start();

this.Close();
like image 84
EZI Avatar answered Oct 25 '25 05:10

EZI