Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms: Application.Exit vs Environment.Exit vs Form.Close

Following are the ways by which we can exit an application:

  1. Environment.Exit(0)
  2. Application.Exit()
  3. Form.Close()

What is the difference between these three methods and when to use each one?

like image 607
Parag Meshram Avatar asked Oct 24 '12 09:10

Parag Meshram


People also ask

How do I exit Winforms application?

The proper method would be Application. Exit() .

What does environment exit do?

Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated. Exit requires the caller to have permission to call unmanaged code.

What is application Exit?

The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.

How do I close a Windows Form in VB net?

If you want to close the form then use Me. Close() instead. The Load event will fire again when you create the new instance.


1 Answers

The proper method would be Application.Exit(). According to the Documentation, it terminates all message loops and closes all windows thus giving your forms the possibility to execute their cleanup code (in Form.OnClose etc).

Environment.Exit would just kill the process. If some form has e.g. unsaved changes it would not have any chances to ask the user if he wants to save them. Also resources (database connections etc.) could not be released properly, files might not be flushed etc.

Form.Close just does what it says: it closes a form. If you have other forms opened (perhaps not now but in some future version of your application), the application will not terminate.

Keep in mind that if you use multithreading, Application.Exit() will not terminate your threads (and thus the application will keep working in the background, even if the GUI is terminated). Therefore you must take measures to kill your threads, either in the main function (i.e. Program.Main()) or when in the OnClose event of your main form.

like image 77
MartinStettner Avatar answered Oct 03 '22 21:10

MartinStettner