What is the best way to get out of a C#app?

Asked

Viewed 125 times

8

1 answer

6


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

But if you have any reason to leave before the Environment.Exit() can be used anywhere in the application without major problems. Note that this can skip some desired finish that would only occur if it came out on Main(), but there is something specific to your application and occurs in rare cases (see documentation). So you want to get out of the Main(), be with a Exit explicit or by an exception, the ideal is that it does not have dependencies to leave or that what needs to be done is always called before an exit outside the Main(). In general you must create a function that must be called before leaving to execute what always needs to be executed before output. Just be careful not to generate errors at this point.

One should avoid leaving by exception, but if it is programming error the only thing to do is to close the same application. If leaving the exception untreated and is a programming error the output will be very similar to the output by return in the Main() since the exception causes the unwinding stack.

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

It would be nice to take a look at Environment.FailFast() that serves for some cases where the exit needs to be immediate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.