tags:

views:

294

answers:

2

From outside of the application, is there any difference between

...
Environment.Exit(2)

and

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

?

+1  A: 

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

David Schmitt
+1 Stating the obvious, but a good point nonetheless.
Brian Rasmussen
Updated question - is there any difference from outside of the application?
Konstantin Spirin
+4  A: 

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...

Jon Skeet
See http://stackoverflow.com/questions/713805/net-finalizers-and-exit0 for details about finalization at end of process.
David Schmitt