问题
My original belief about Environment.Exit was this:
If called from the default AppDomain, the process would terminate.
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