What is the best way to exit a C # application?

8

The most common way is to exit with return in Main() . But I saw that there are Environment.Exit() . and Application.Exit() .

When should we use each?

    
asked by anonymous 18.04.2017 / 14:26

1 answer

6

The best way is return in Main() . It's the least traumatic.

But if you have any reason to leave before Environment.Exit() can be used anywhere in the application without major problems. Note that this can skip some desired termination that would only occur if it exits in Main() , but there is something specific to your application. So if you want to get out of Main() , either with an explicit exit or an exception, the ideal is that you do not have dependencies to exit or that what needs to be done is always called before an exit out of Main() . In general you must create a function that must be called before exiting to perform what must always be performed before the output. Just be careful not to generate errors at this point.

Exception should be avoided, but if it is a programming error, the only thing to do is shut down the application itself. If you leave the exception unhandled and it is a programming error, the output will be very similar to the output of return in Main() since the exception causes the stack unwinding .

Application.Exit() is part of Windows Forms, you can see the namespace that it is. It does the same as the previous form, but it does the correct closing of the forms by closing the message loop of the windows operating system, most likely Windows.

    
18.04.2017 / 14:35