1

I was debugging a simple aplication that has three forms, and I figured out that when I close a form, and then I opened again (clicking on a button that shows the respective form), the object that represents the form is created again. I think that this consume resources unnecessarily.

So, how can I create only one instance of all forms to use while the program is executed?

Pablo De Luca
  • 795
  • 3
  • 15
  • 29

2 Answers2

4

You should be able to hook up to closing events and all that you would need would be to set the form you are closing to hidden instead of actually closing it. The form would then be made available through a Singleton, which takes care of the initialization and rendering of the form itself.

Note that you might still want to release any other resources which the form you are hiding uses, such as files and/or connections.

As a side note, keep in mind that keeping forms in memory when you are not using them will increase the memory footprint of your application.

npinti
  • 51,780
  • 5
  • 72
  • 96
1

What you are describing sounds like the Singleton Pattern.

private MyForm() {

}

private static MyForm _instance;
public static MyForm Instance => _instance ?? (_instance = new MyForm());

It is possible, the Designer starts to mess around because the Constructor is private. Furthermore you cant Dispose/Close the Forms anymore. That forces you to make the Form invisble instead of get rid of them

lokusking
  • 7,396
  • 13
  • 38
  • 57