3.9 Unload Assemblies and Application Domains


Problem

You need to unload assemblies or application domains at run time.

Solution

There's no way to unload individual assemblies. You can unload an entire application domain using the static AppDomain.Unload method, which has the effect of unloading all assemblies loaded into the application domain.

Discussion

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 . (This limitation is likely to be resolved in a future version of the .NET Framework.)

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 .




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net