Difference between Environment.Exit and simple return 2 from Main

回眸只為那壹抹淺笑 提交于 2019-12-04 16:57:29

问题


From outside of the application, is there any difference between

...
Environment.Exit(2)

and

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

?


回答1:


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




回答2:


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




回答3:


If you are doing a Unit Test and calling Main

Program.Main(args);

then Environment.exit will always reflect a failure. Where as using return will work as expect.



来源:https://stackoverflow.com/questions/1470225/difference-between-environment-exit-and-simple-return-2-from-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!