Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

sometimes, when I use Form.close() when debugging my program, although the form is closed, the application is still running. I noticed this behaviour when using the msgbox function.

I have no thread nor timer running, so what is the best way to close a .NET app? I am using VB.NET.

Thanks

like image 791
GianT971 Avatar asked Feb 12 '11 04:02

GianT971


3 Answers

The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.

The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close method of all forms that you've shown during the course of application, not just the startup/main form.

The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).

The settings I'm talking about are highlighted here:

   Visual Studio Project Properties

But primarily, note that you should never have to call Application.Exit in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.

like image 172
Cody Gray Avatar answered Nov 26 '22 19:11

Cody Gray


In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

like image 36
Josh Avatar answered Nov 26 '22 18:11

Josh


If you are in a loop (Do While, For, ...) and you call Me.Close(), you should follow with an Exit command (Exit Do, ...) or a Return() to force the message processing to terminate properly. I caught programs hanging due to this.

like image 21
Randall Spychalla Avatar answered Nov 26 '22 20:11

Randall Spychalla