Does Environment.Exit called from any AppDomain exit the entire process if not IsDefaultAppDomain?

假装没事ソ 提交于 2019-12-23 15:25:00

问题


My original belief about Environment.Exit was this:

  1. If called from the default AppDomain, the process would terminate.

  2. If called from an AppDomain other than default, the AppDomain would terminate and push the exit code into the return of AppDomain.ExecuteAssembly.

This seemed logical to me, as it would forseeably be undesirable for a loaded AppDomain to unintentionally kill the entire process due to calling Environment.Exit instead of ending at the "}" like the accepted answer of https://stackoverflow.com/questions/3971101/c-sharp-whats-the-best-way-to-end-a-program speaks of.

However the MSDN description of Environment.Exit is as follows:

Terminates this process and gives the underlying operating system the specified exit code.

So this makes me wonder, does Environment.Exit kill the entire process as the MSDN says, or does it work like my original assumption?


回答1:


The MSDN library article is accurate of course. And no, you cannot just call Environment.Exit() and hope it will work, it has a CAS demand. A tall one, the code must be trusted to run dangerous code, SecurityPermissionFlag.UnmanagedCode. You normally only get that in full trust.

Sandboxing code in an AppDomain is pretty easy, this MSDN page shows how.




回答2:


I've created a test solution to test this, and it appears the MSDN is correct.

If Environment.Exit is called from anywhere, the entire process will exit. With that in mind, Environment.Exit should only be used if you desire to kill the process your code is running in, not simply to exit your application.

Calling Environment.Exit to exit your application, might cause issues for other applications which load your software in an AppDomain.




回答3:


I would say that Environment.Exit should ideally never be used, most likely there's a design fault in the application if it's used. A ".NET process" will exit automatically when there's no foreground threads running anymore. If you exit your main thread, and there's no other foreground threads, then your app will exit. You should be able to keep track of all your foreground threads, and have a safe way to make them exit, one-by-one.

If you have to rely on Environment.Exit then you have a problem.



来源:https://stackoverflow.com/questions/15143810/does-environment-exit-called-from-any-appdomain-exit-the-entire-process-if-not-i

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