Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Environment.Exit and simple return 2 from Main

Tags:

.net

exit-code

From outside of the application, is there any difference between

...
Environment.Exit(2)

and

static int Main()
{
    ...
    return 2;
}

?

like image 206
Konstantin Spirin Avatar asked Sep 24 '09 07:09

Konstantin Spirin


People also ask

What is environment exit?

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.

Is exit the same as return?

return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used.

Should I use exit or return in C?

For the most part, there is no difference in a C program between using return and calling exit() to terminate main() .


2 Answers

Environment.Exit(2) can be used everywhere. return 2 only within the Main() function.

like image 41
David Schmitt Avatar answered Oct 23 '22 07:10

David Schmitt


The most obvious difference is that you can call Environment.Exit from anywhere in your code. Aside from that:

  • Main finishing won't terminate the process if there are other foreground threads executing; Environment.Exit will take down the process anyway.
  • Environment.Exit terminates the process without unwinding the stack and executing finally blocks (at least according to my experiments). Obviously when you return from Main you're already at the top level as far as managed code is concerned.
  • Both give finalizers a chance to execute before the process really shuts down
  • Environment.Exit demands the appropriate security permission, so won't work for less trusted apps.

Having seen the question update, I'm not entirely sure what you mean. In both cases the process will just exit with a code of 2...

like image 161
Jon Skeet Avatar answered Oct 23 '22 07:10

Jon Skeet