Reputation: 255
What is the difference between Environment.Exit(0);
and Environment.Exit(Environment.ExitCode);
?
I've used both, and they seem to do the same thing. So which one should I use?
Upvotes: 0
Views: 3077
Reputation: 1484
The default value of Environment.ExitCode
is 0 so normally, there won't be a difference. But since ExitCode
is an integer it can be set to any value e.g Environment.ExitCode = 1
. If a system fails it can set ExitCode to 1 and when the environment exits on either Environment.Exit(Environment.ExitCode)
or just end of the program it would have ExitCode
1 instead of 0. Anything other than 0 would indicate an error.
Upvotes: 2
Reputation: 59259
I've used both, and they seem to do the same thing.
As others have already noted, that's because the default value for ExitCode
is 0.
So which one should I use?
Typically, if you call Exit()
, you a) have a good reason for that and b) you want to terminate as soon as possible with all the disadvantages described in the remarks section.
Therefore you would
Environment.Exit(0);
and instead let the void Main()
method run to its end in a normal way.Environment.Exit(Environment.ExitCode);
because that would imply that the reason for the termination was set a while back.Environment.Exit(ERRORCODE);
, likely with a meaningful constant instead of a magic numberSo the real answer is: don't use it at all, if possible.
Instead you might want to try Window.Close()
to close a single window or Application.Exit()
, which closes all windows and gets you back to the Main()
method and out of the Application.Run()
method call.
If that's not sufficient to terminate your program and you still see it in Task Manager, it has a foreground thread running, e.g. a thread that saves the users work. You don't want to terminate that, because it could result in a corrupted file.
There is a concept of a boolean isRunning
or _shouldStop
variable to terminate threads.
If you don't know why your application is not terminating, attach a debugger and have a look at the callstack of the remaining threads.
Upvotes: 3
Reputation: 91
Environment.ExitCode is a int static property which by default takes the value of 0. This is because int is a Value Type and the default value is 0.
So, if in your code you don't set the value of Environment.ExitCode other than 0 ,then they will be the same thing.
Upvotes: 2