Application closure

What is the best practice when closing a C # application?

I read that you can use:

Environment.Exit(0); or Application.Exit(); 

But what is the difference?

In addition, with regard to the environment. Exit (0), I used exit codes before I worked with Java, but I never understood their purpose. What role do they play when they exit the application in C #?

+65
c #
Aug 22 '11 at 10:25
source share
4 answers

System.Windows.Forms.Application.Exit() - informs all mailing messages that they should be completed, and then closes all application windows after processing messages. This method stops all running message cycles in all threads and closes all application windows. This method does not force the application to close. The Exit() method is usually called from a message loop and forces Run() return. To exit the message loop for the current thread only, call ExitThread() . This is a challenge to use if you are using a Windows Forms application. Typically, use this call if you called System.Windows.Forms.Application.Run() .

System.Environment.Exit(exitCode) - terminates this process and gives the base operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode rights. If you do not, a SecurityException . This is a call to use if you are launching a console application.

I hope best to use Application.Exit

See also these links:

+67
Aug 22 '11 at 10:30
source share

Application.Exit for Windows Forms applications - it informs all message pumps that they must stop, waits for them to complete event processing, and then shuts down the application. Please note that this does not necessarily force the application to exit.

Environment.Exit applicable to all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general, you should use Application.Exit in Windows Forms and Environment.Exit applications in console applications (although I prefer the Main method / entry point to execute before completion rather than calling Environment.Exit in console applications).

See the MSDN documentation for more information.

+17
Aug 22 '11 at 10:28
source share

What role do they play when they exit the application in C #?

The same as in any other application. They are mainly returned to the caller. Irrelvant, if you started by double-clicking iicon. It is relevant to call a batch file, which decides whether the application is running in the return code. SO, if you are not writing the program he needs, the returned dcode does not matter.

But what is the difference?

One of the environments is one of System.Windows.Forms? .Application. Functionally, there should not be much difference.

0
Aug 22 '11 at 10:28
source share

for me the best consolation is

  Thread.CurrentThread.Abort(); 

and force close the application.

0
Apr 06 '18 at 15:27
source share



All Articles