One of the great capabilities of the AppDomain is that it allows for uninstallation. Uninstalling the AppDomain causes the CLR to unload all the assemblies in the AppDomain. The loader heap of the AppDomain is also released. In order to unload an AppDomain, you can call the AppDomain's static method unload. This causes the CLR to perform a series of actions to gracefully unload the specified AppDomain.
- The CLR suspends all threads in the process that have executed managed code.
- The CLR checks the wired stacks to see if those threads are executing the code in the AppDomain that is being unloaded, or those threads will return to the AppDomain to be unloaded at some point. On any stack, if there is a appdomain,clr ready to unload, the corresponding thread is forced to throw a ThreadAbortException exception (while resuming the execution of the thread). This causes the thread to expand, executing the contents of all the finally blocks encountered during the unwind process to execute the resource cleanup code. If no code captures ThreadAbortException, it will eventually become an unhandled exception, and the CLR will "eat" the exception;
The thread terminates, but the process continues to run. This is very special, because the CLR terminates the process for all other unhandled exceptions.
- When all the threads found in step 2nd leave the AppDomain, the CLR traverses the heap and sets a flag for each proxy object that references objects created by the unloaded AppDomain. These proxy objects now know that the real object they are referencing is gone. If any code calls a method on an invalid proxy object, the method throws a appdomainunloadedexception.
- The CLR enforces garbage collection and reclaims the memory that is occupied by any objects created by the AppDomain that is now unloaded. The finalize methods of these objects are called, giving the object the opportunity to completely clean up the resources they occupy.
- The CLR resumes execution of all remaining threads. The thread that calls the AppDomain.Unload method will continue to run, and the call to AppDomain.Unload is synchronized.
In the Ch22-1-appdomain application, all work has a thread to do. Therefore, it is impossible to have another thread in the AppDomain to unload whenever AppDomain.Unload is called. Therefore, the CLR does not have to throw any threadabortexception exceptions.
By the way, when a thread calls the AppDomain.Unload method, the CLR gives them 10 seconds to leave for the threads in the AppDomain to unload. After 10 seconds, if the thread calling the AppDomain.Unload method has not yet returned, the CLR throws a CannotUnloadAppDomainException exception, and the AppDomain may or may not unload in the future.
Section III: Uninstalling the AppDomain