The only way to unload an assembly is to unload the application domain in which the assembly is loaded. Unfortunately, unloading an application domain will unload all of the assemblies that have been loaded into it. This might seem like a heavy-handed and inflexible approach, but with appropriate planning of your application domain and assembly loading structure, it isn't overly restrictive.
You unload an application domain using the static AppDomain.Unload method and passing it an AppDomain reference to the application domain you wish to unload. You can't unload the default application domain created by the CLR at startup. This code fragment demonstrates the Unload method.
// Create a new application domain AppDomain newDomain = AppDomain.CreateDomain("New Domain"); // Load assemblies into the application domain § // Unload the new application domains AppDomain.Unload(newDomain);
The Unload method stops any new threads from entering the specified application domain and calls the Thread.Abort method on all threads currently active in the application domain. If the thread calling the Unload method is currently running in the specified application domain (making it the target of a Thread.Abort call), a new thread is started to carry out the unload operation. If there's a problem unloading an application domain, a System.CannotUnloadAppDomainException is thrown by the thread performing the unload operation.
While an application domain is unloading, the CLR calls the finalization method of all objects in the application domain. Depending on the number of objects and nature of their finalization methods, this can take an arbitrary amount of time. The AppDomain.IsFinalizingForUnload method returns true if the application domain is unloading and the CLR has started to finalize contained objects; otherwise, it returns false.
No comments:
Post a Comment